This blog will soon be merged with

JavaByPatel

which explains each solution in detail, to visit new blog, click JavaByPatel

Thursday, 11 June 2015

Print Singly linked list in reverse order using recursive approach


package linkedlist.singly;

//Print Singly linked list in reverse order
//Example:
//Input  = 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80
//Output = 80  70  60  50  40  30  20  10
public class PrintLinkedListReverse {
 Node startNode=null;
 
 public static void main(String[] args) {
  new PrintLinkedListReverse();
 }
 public PrintLinkedListReverse() {
  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; 
  printReverse1(startNode);
 }
 
 //Recursive approach.
 private void printReverse1(Node startNode){
  if(startNode==null){
   return;
  }
  printReverse1(startNode.getNext());
  System.out.print(startNode.getData() + " " );
 }
}



No comments:

Post a Comment