Saturday, January 14, 2012

Reversing a singly linked list

Function to reverse a singly linked list

ITERATIVE APPROACH

void reverse(node * head)
{
node * prev=NULL,*tmp;
while(head)
{
tmp=head->next;
head->next=prev;
prev=head;
head=temp;
}
head=prev;
}

This will reverse a linked list in O(n) time complexity

No comments: