Display linked list in reverse order in Java

In order to display linked list in reverse order we can use fundamental of recursion - call method recursively and display node while returning from where it was called.
Sample code for displaying data in reverse order:
private void displayLinkedListInReverseOrder(Node head) {
 if (head == null)
  return;
 /* Recursive call for next node */
 displayLinkedListInReverseOrder(head.next);
 System.out.println(head.data);
}
Explanation :- Method displayLinkedListInReverseOrder(node) is called recursively for each node and when end of list or list is empty, method call simply returns to caller. While returning to caller head element is displayed.

Below is complete sample program for displaying linked list in reverse order:-
package com.devinline.linkedlist;

public class DisplayLinkedList {
 private void displayLinkedListInReverseOrder(Node head) {
  if (head == null)
   return;
  /* Recursive call for next node */
  displayLinkedListInReverseOrder(head.next);
  System.out.print(head.data + " ");

 }

 class Node {
  public int data;
  public Node next;

  public Node(int data) {
   this.data = data;
   this.next = null;
  }
 }

 public static void main(String[] args) {
  DisplayLinkedList cyc = new DisplayLinkedList();
  Node node1 = cyc.new Node(12);
  Node head = node1;
  Node node2 = cyc.new Node(18);
  Node node3 = cyc.new Node(172);
  Node node4 = cyc.new Node(62);
  Node node5 = cyc.new Node(632);
  Node node6 = cyc.new Node(192);
  head.next = node2;
  head.next.next = node3;
  head.next.next.next = node4;
  head.next.next.next.next = node5;
  head.next.next.next.next.next = node6;
  System.out.println("Original list is:  12 18 172 62 632 192");
  System.out.print("Display in reverse order : ");
  cyc.displayLinkedListInReverseOrder(head);

 }

}
=======Sample output==========
Original list is:  12 18 172 62 632 192
Display in reverse order : 192 632 62 172 18 12
============================

Read also :-
How to reverse a linked list using recursion.

1 Comments

Previous Post Next Post