Print Linked List In Reverse Order in Java

Print Linked List In Reverse Order in Java.


Print linked list in reverse order in java. print singly linked list in reverse order using recursion. java program to print linked list in reverse.

Let's understand the problem statement in simple words, 
You are given a Singly linked list, print the linked list in reverse way, from end to start.

Example: 
Input:     10 -> 20 -> 30 -> 40 -> 50 -> null
Output:  50      40     30      20      10
 



Algorithm

Printing Linked list in Reverse order using Recursion is very easy. 

STEP 1: Recursively iterate the linked list till you not reach null that is the end of the linked list.
STEP 2: When you reach null, return.
STEP 3: While returning from each recursive call, Print the Node data and you are done.

You are printing node data when recursive call is getting returned, that is why linked list is printed in reversed way.

For Reversing the linked list, please refer:  Reverse a Linked list in Java

Let's understand the recursive stack trace in below diagram and solution will be more clear.



Java Program to Print Linked List In Reverse Order.

package javabypatel;

//Print Singly linked list in reverse order
public class PrintLinkedListInReverseOrder {
 Node startNode=null;

 public static void main(String[] args) {
  new PrintLinkedListInReverseOrder();
 }
 public PrintLinkedListInReverseOrder() {
  Node n1 = new Node(10);
  Node n2 = new Node(20);
  Node n3 = new Node(30);
  Node n4 = new Node(40);
  Node n5 = new Node(50);
  Node n6 = new Node(60);
  Node n7 = new Node(70);
  Node n8 = new Node(80);

  n1.setNext(n2);
  n2.setNext(n3);
  n3.setNext(n4);
  n4.setNext(n5);
  n5.setNext(n6);
  n6.setNext(n7);
  n7.setNext(n8);

  startNode = n1; 
  printLinkedListInReverse(startNode);
 }

 //Recursive approach.
 private void printLinkedListInReverse(Node startNode){
  if(startNode==null){
   return;
  }
  printLinkedListInReverse(startNode.getNext());
  System.out.print(startNode.getData() + " " );
 }
}

Node.java
package javabypatel;

public class Node {
 private int data;
 private Node next;

 public Node(int data) {
  this.data = data;
 }
 public void setNext(Node next) {
  this.next = next;
 }
 public Node getNext() {
  return next;
 }
 public int getData() {
  return data;
 }
 public void setData(int data) {
  this.data = data;
 }
}


You may also like to see


Count trailing zeros in factorial of a number.

Swap two numbers In Java without using third variable - Best Approach.

Breadth First Search(BFS) Vs Depth First Search(DFS) with example in Java

Can static method be called using object in java

Method overriding and Method hiding Interview Question in Java.

When to use SOAP over REST Web Service. Is REST better than SOAP?.

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment