Now having that idea in mind we can apply it to our previous problem of reversing part of a linked list.
Loop stops when currNode becomes null, at this point prevNode is at the last node in list, we assign it to head pointer making it begining of the list.Īnd gif to illustrate the process of linked list reversal for a clearer picture.> Move prevNode and currNode one step forward. > Make the next of currNode to prevNode. We go through the linked list performing the following operations.We first initialize 3 pointers, prevNode, currNode, nextNode.To reverse a linked list all we need to do is change the pointers linking the nodes to point backwards and make the head pointer point to the last node and next pointer of previous head point to null making it the end of the list.ħ -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> NULL Algorithm:
#REVERSE LINKED LIST HOW TO#
We need to understand how to go about reversing a linked list then coming to the main problem, all we need to do is to apply that knowledge to some part of the whole linked list. To reverse part of a linked list we first need to break down the problem, into a smaller manageable sub-problems after which we will use knowledge gained from solving the sub-problem and apply it to solving the larger problem. Let us get started with Reverse part of Singly Linked List.
Approach 2 to Reverse part of Singly Linked List.Approach 1 to Reverse part of Singly Linked List.It takes linear time O(N) to Reverse part of Singly Linked List. In this post, we have demonstrated ways in which we can not only reverse a singly linked list but also some part of Singly Linked List.