Please navigate to the bottom of the page for Table of Contents

Sunday, May 15, 2011

Reverse a Linked List

This is a short post but this topic deserved it’s own post. As I had mentioned before, the order in which you manipulate the pointers is extremely critical. Reversing a linked list can become quite complicated if you do not pay close attention to the order.

Consider the following linked list made up of 4 nodes. The head pointer points to the start of the list.  

image

To reverse this list, we need 3 additional pointers.  We need a currentNode pointer to traverse through the list, a nextNode pointer to save the next node in the list,  and finally, a prevNode pointer to keep track of the last node in the new list as we keep on reversing the input list. So, in essence, here is the pseudo algorithm to reverse the list:

  • Initialize currentNode pointer to the start of the list and prevNode to NULL (as the new list is currently pointing to NULL).
  • While currentNode is not NULL
    • Save the next node in nextNode
    • Set the currentNode to point to the prevNode. 
    • Move the prevNode to the currentNode.
    • Move the currentNode pointer to the nextNode.

Look at the following representations to better understand the concept outlined.

Step 1: setup

image

 

Step 2: Set the currentNode to point to the prevNode

image

Step 3: Move the pointers

image

Add the process continues till the list has been reversed. As the last step, you need to reset the head pointer to point to the prevNode as that is now the current head of the reversed list. Once you have understood the logic, the code part is actually quite simple as shown in the function below.

void Reverse()
{
// Initialize currentNode pointer to the start of the list
// and prevNode to NULL
// (as the new list is currently pointing to NULL).
Node *currentNode = head;
Node *prevNode = NULL;
Node *nextNode = NULL;

while (currentNode != NULL)
{
// Save the next node in nextNode
nextNode = currentNode->next;
// Set the currentNode to point to the prevNode.
currentNode->next = prevNode;
// Move the prevNode to the currentNode.
prevNode = currentNode;
// Move the currentNode pointer to the nextNode.
currentNode = nextNode;
}

// reset the head pointer to point to the prevNode
// as that is now the current head of the reversed list
head = prevNode;
}


3 comments:

  1. Thanks Nikhil, your blog is a great resource.

    VR

    ReplyDelete
  2. Perhaps a recursive solution?

    def reverse(head, prev=nil)
    reverse(head.next, head)
    head.next = prev if head
    end

    ReplyDelete
  3. one of the best explainations so far.. (y)

    ReplyDelete