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);
}
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);
}
}
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.
0 comments:
Post a Comment