C Program Reverse A Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node* createList(struct Node *head, int n)
{
int i, item;
struct Node *nw, *temp;
for(i = 0; i < n; i++)
{
nw = (struct Node*)malloc(sizeof(struct Node));
nw->next = NULL;
printf("Enter Data: ");
scanf("%d", &item);
nw->data = item;
if (i == 0)
{
head = nw;
temp = head;
}
else
{
temp->next = nw;
temp = temp->next;
}
}
return head;
}
void disp(struct Node *head)
{
struct Node *temp = head;
while(temp != NULL)
{
printf("%d ",temp->data);
temp = temp->next;
}
}
struct Node* reverse(struct Node *head)
{
struct Node *prev = NULL, *next = NULL;
struct Node *curr = head;
while(curr != NULL)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
int main()
{
struct Node *head = NULL;
head = createList(head, 5);
disp(head);
head = reverse(head);
printf("\n");
disp(head);
return 0;
}
Enter Data: 5
Enter Data: 4
Enter Data: 3
Enter Data: 2
Enter Data: 1
5 4 3 2 1
1 2 3 4 5
--------------------------------
Process exited after 4.487 seconds with return value 0
Press any key to continue . . .