Reverse a Linked List


Today we will discuss how to reverse a linked list. Proceed if you have basic knowledge of linked list otherwise you can read this post on where I have explained you about linked list. Let me explain you what a reversed linked list is. Suppose we have a linked list 1->2->3->4->5->NULL then the reverse of this list will be 5->4->3->2->1->NULL. So, let's discuss how we can reverse a linked list.

Procedure

1. First we will make a linked list.
2. Now we will traverse the linked list.
3. While traversing when we will reach the first node we will make it point NULL.
4. Then at each node we will make that node point to the previous node.
5. When we will reach the last node then we will update head and initialize it with the address of last node.

Reverse a Linked List


Code



Explanation of Code( line by line)

1. First we will write a simple code of linked list which will have 2 functions:
     - insert() - which will insert elements in the linked list.
     - disp() - which will display the linked list.
2. Insert some values in the linked list.
3. Now we have created a function named reverse() to reverse the linked list.
4. In the reverse() function we have made 3 pointer to node variables:
  • prev : Which will point to the node previous to current node.
  • current : Which will point to the current node.
  • forward : Which will point to the node ahead of current node.
5. Initially prev, current and forward are initialized with head.
6. Then forward is initialized with the next node after current.
     forward=current->next;
7. Then current->next is initialized to NULL because this current is the first node and after reversing the list it will become last node so it shall point to NULL. 
8. Then we have started a loop to traverse the list till current!=NULL and forward!=NULL
9.In the loop we have assigned prev with the address of current and current with the address of forward and forward with forward->next so that all 3 pointer to node can increment.
    prev=current;
    current=forward; 
10. Then we have assigned the current->next with the address the prev because in order to reverse the linked list each node shall point to its previous node.
    current->next=prev;
11. After while loop is over we have assigned head the address of current node because when the loop will be over current will be at last node and the last node will become the first node after reversing and first node is always pointed by head node.


Post a Comment (0)
Previous Post Next Post