This post is completed by 3 users
|
Add to List |
20. Reverse a Linked List
Objective: Reverse the given linked list.
Input: A Linked List Output: Reversed Linked List
Example:
Input : ->30->25->20->15->10->5 Reversed : ->5->10->15->20->25->30
NOTE : Click Reverse a Linked List - Part 2 to see the another implementation of this problem.
Approach:
Iterative:
- Create 3 nodes, currNode, PrevNode and nextNode.
- Initialize them as currNode = head; nextNode = null;prevNode = null;
- Now keep reversing the pointers one by one till currNode!=null.
- At the end set head = prevNode;
while (currNode!= null){ nextNode = currNode.next; currNode.next = prevNode; prevNode = currNode; currNode = nextNode; }
Walk Through-
Note: If Image above is not clear, either zoom your browser or right click on image and open in a new tab.
Output:
->5->4->3->2 reversed ->2->3->4->5