//Program to reverse a single linked list
//Assumption: Each item in the list, is added as head in the list
// Improv:- modify such that the element is pushed into the last of list
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void reverse(struct node **head)
{
struct node *travnode = NULL;
struct node *prevnode = NULL;
struct node *nextnode = NULL;
travnode = *head;
while(travnode !=NULL)
{
//Storing the next node is important
nextnode = travnode->next;
travnode->next = prevnode;
prevnode = travnode;
travnode = nextnode;
}
*head = prevnode;
printf("%s\n", "Exiting reverse");
}
static void pushlist(struct node **head, int data)
{
struct node *currentnode = NULL;
currentnode = malloc(sizeof(struct node *));
currentnode->data = data;
currentnode->next = *head;
*head = currentnode;
}
void print(struct node *headnode)
{
struct node* travnode = headnode;
while(travnode!=NULL) {
printf("%d\t", travnode->data);
travnode = travnode->next;
}
}
int main()
{
int a= 0, b=0, c=0, d=0, e=0;
struct node *head = NULL;
printf(" Enter 5 nos :\n");
scanf( "%d %d %d %d %d", &a, &b, &c, &d, &e);
pushlist(&head, a);
pushlist(&head, b);
pushlist(&head,c);
pushlist(&head,d);
pushlist(&head,e);
print(head);
reverse (&head);
print(head);
return 0;
}
Sample Output:
Enter 5 nos :
99 88 77 66 55
55 66 77 88 99 Exiting reverse
99 88 77 66 55