Home > Algorithms > Reverse a singly linked list

Reverse a singly linked list

July 7, 2012

Suppose that a linked list has elements in the order

10 20 30 40 50

After reversing the output should be
50 40 30 20 10

This code will do the work

NODE reverse(NODE first)
{
NODE cur,temp;
cur = NULL;
while(first != NULL)
{
temp = first;
first = first->link;
temp->link = cur;
cur = temp;
}
return cur;
}

Recursive Solution;

if(first->next->next != NULL)
reverse(first->next);
I    if(first->next->next == NULL)
Node temp = first->next;
first->next = first->next->next;
temp->next = first;
Advertisements
Categories: Algorithms
%d bloggers like this: