This post is completed by 3 users

  • 0
Add to List
Beginner

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:

  1. Create 3 nodes, currNode, PrevNode and nextNode.
  2. Initialize them as currNode = head; nextNode = null;prevNode = null;
  3. Now keep reversing the pointers one by one till currNode!=null.
  4. At the end set head = prevNode;
while (currNode!= null){
     nextNode = currNode.next;
     currNode.next = prevNode;
     prevNode = currNode;
     currNode = nextNode;
}

Walk Through-

Linked List Reversal

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