Monday, May 7, 2012

Q. How to reverse a linked list.

Consider the following linked list ( A-->B-->C-->D-->NULL) the expected output is (D-->C-->B-->A-->NULL).

With one pointer to the Node 'A' say current we can access the node 'A' and node 'B'. (current-->next). If we point the next node for B to A we get the following (A-->B-->A) however we lose the next node 'C' and also have a loop A-->B-->A information.

We can fix this by trying with 2 extra nodes. Node 'prev' points to A and node current points to B. So we can break the node link A-->B and point B-->A ( current points to prev) however we still lose the node C information.

Lets us try this approach now with 3 nodes. prev = NULL , current = A, next = B. We continue traversing to the end of the list while updating the 'current' node to point to 'prev' and moving the (prev, current and next nodes by one)

Recursive Solution

This solution is more intutive. We are essentially trying to traverse till the end of the list and point each node next to its previous node i.e. traverse the list from the TAIL node (D here) D to C to B to A.

We use the same logic as above however we now recurseively traverse the linked list till the end of loop and point the current node to the prev node.

In the above example we recurse till current = 'D' and prev is 'C' then point the current D next to C i.e. D-->C.

When we come of out the recursive call end noe current is C and prev is B so C-->B, so on till the head node