Reverse a linked list in java

Previous
Next

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

In this post, we will see how to reverse a linked list in java.

This is one of popular interview question.

Java Linked List Interview Programs:

There can be two solution to reverse a linked list in java

  • Iterative
  • Recursive

Iterative

Logic for this would be:

  • Have three nodes i.e previousNode,currentNode and nextNode
  • When currentNode is starting node, then previousNode will be null
  • Assign currentNode.next to previousNode to reverse the link.
  • In each iteration move currentNode and previousNode by  1 node.

Java program to reverse a linkedlist will be :

Run above program, you will get following output:

Recursive

Base case: Base case for this would be either node is null or node.next is null
For recursive solution, replace reverseLinkedList of above program to below function

Output of this program will be same as above program.
Now lets understand logic for above recursive program.
5->6->7->1->2
Above function will terminate when last node(2) ‘s next will be null.so while returning when you reach at node with value 1,If you closely observe node.next.next=node is actually setting 2->1(i.e. reversing the link between node with value 1 and 2) and node.next=null is removing link 1->2. So in each iteration, you are reversing link between two nodes.
Below diagram will make it clear

Please go through java interview programs for more such programs.

That’s all about reverse a linked list in java.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




5 Comments

  1. Sajjad Islam July 29, 2015
  2. rohit December 30, 2015
    • MKB January 14, 2016
  3. calvinraveenthran January 10, 2016
  4. Jitendra Chopra September 21, 2018

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog