An interesting method to print reverse of a linked list | Java program to print reverse of list ; Represents node of a linkedlist ; Function to reverse the linked list ; For each node , print proper number of spaces before printing it ; use of carriage return to move back and print . ; Function to push a node ; Function to print linked list and find its length ; i for finding length of list ; Driver code ; Start with the empty list ; list nodes are as 6 5 4 3 2 1 ; printlist print the list and return the size of list ; print reverse list with help of carriage return function
import java . io . * ; import java . util . * ; class Node { int data ; Node next ; Node ( int val ) { data = val ; next = null ; } } public class GFG { static void printReverse ( Node head , int n ) { int j = 0 ; Node current = head ; while ( current != null ) { for ( int i = 0 ; i < 2 * ( n - j ) ; i ++ ) System . out . print ( " ▁ " ) ; System . out . print ( " \r " + current . data ) ; current = current . next ; j ++ ; } } static Node push ( Node head , int data ) { Node new_node = new Node ( data ) ; new_node . next = head ; head = new_node ; return head ; } static int printList ( Node head ) { int i = 0 ; Node temp = head ; while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . next ; i ++ ; } return i ; } public static void main ( String args [ ] ) { Node head = null ; head = push ( head , 1 ) ; head = push ( head , 2 ) ; head = push ( head , 3 ) ; head = push ( head , 4 ) ; head = push ( head , 5 ) ; head = push ( head , 6 ) ; System . out . println ( " Given ▁ linked ▁ list : ▁ " ) ; int n = printList ( head ) ; System . out . println ( " Reversed ▁ Linked ▁ list : ▁ " ) ; printReverse ( head , n ) ; System . out . println ( ) ; } }