Monday, November 2, 2015

Print Singly Linked List in Reverse Order Recursively in Java

Arrays have got constant size restriction when they are created so it is expensive to resize them dynamically in an application. Instead of using arrays for resizing dynamic structure requirements, singly linked list data structure can be used.

Singly linked list has got a node based structure where each node has got next and data fields.


Above is a singly linked list with 1-2-3-4-5 elements.

In order to print data elements of each node of a singly linked list data structure in Java following forwardPrint and reversePrint methods can be used.

reversePrint is a recursive method and assumes that the head node is not null.


package basics;

public class LinkedList {

 static class Node
 {
  Node next;
  int data;
 }

 private Node head;
 
 public LinkedList(Node pHead) {
  head = pHead; 
 } 
 
 public void forwardPrint()
 {
  forwardPrint(head);
 }
 
 private void forwardPrint( Node node )
 { 
  Node current = head;
  while( current!=null )
  {
   System.out.println(current.data);
   current = current.next;
  }
 }
 
 public void reversePrint()
 {
  reversePrint(head);
 }
 
 private void reversePrint( Node node )
 {
  if( node.next != null )
   reversePrint(node.next);
  
  System.out.println(node.data);
 }
 
 public static void main(String[] args) {
  
  Node node1 = new Node();
  node1.data = 1;
  Node node2 = new Node();
  node2.data = 2;
  Node node3 = new Node();
  node3.data = 3;
  Node node4 = new Node();
  node4.data = 4;
  Node node5 = new Node();
  node5.data = 5;
  node1.next = node2;
  node2.next = node3;
  node3.next = node4;
  node4.next = node5;
  node5.next = null;
  
  LinkedList list = new LinkedList(node1);
  System.out.println("Forward Print Linked List = ");
  list.forwardPrint();
  System.out.println("Backward Print Linked List = ");
  list.reversePrint();
 }
}



Node objects are created separately and node1 object sent as the head of the linked list. Create a LinkedList.java file in your workspace.

When the main method inside the LinkedList class executed it is going to print :

Forward Print Linked List =
1
2
3
4
5
Backward Print Linked List =
5
4
3
2
1

No comments:

Post a Comment