Reversing a linked list

Reversing is a singly linked list is very interesting piece of code and I think it is one of the important datastructure questions asked in interviews. I saw this very interesting discussion here
and this peice of code looks good to me:

Node *Reverse (Node *p)
{
Node *pr = NULL;
while (p != NULL)
{
Node *tmp = p->next;
p->next = pr;
pr = p;
p = tmp;
}
return pr;
}

The logic is to reverse the pointers. There is also a recursive solution to this problem but i guess the above solution is the best bet. If its a doubly linked list, swapping the next and prev pointers and changing the tail as head would be the solution.

0 comments: