Recursively Reversing a linked list (A simple implementation)
Given pointer to the head node of a linked list, the task is to recursively reverse the linked list. We need to reverse the list by changing links between nodes.
Input : Head of following linked list 1->2->3->4->NULL Output : Linked list should be changed to, 4->3->2->1->NULL Input : Head of following linked list 1->2->3->4->5->NULL Output : Linked list should be changed to, 5->4->3->2->1->NULL Input : NULL Output : NULL Input : 1->NULL Output : 1->NULL
- We return the pointer of next node to his previous(current) node and then make the previous node as the next node of returned node and then returning the current node.
- We first traverse till the last node and making the last node as the head node of reversed linked list and then applying the above procedure in the recursive manner.
We have discussed an iterative and two recursive approaches in previous post on reverse a linked list.
In this approach of reversing a linked list by passing a single pointer what we are trying to do is that we are making the previous node of the current node as his next node to reverse the linked list.
Given linked list 85 15 4 20 Reversed Linked list 20 4 15 85
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.