An interesting method to print reverse of a linked list | Link list node ; 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 ; 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
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def printReverse ( head_ref , n ) : NEW_LINE INDENT j = 0 NEW_LINE current = head_ref NEW_LINE while ( current != None ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i < 2 * ( n - j ) ) : NEW_LINE INDENT print ( end = " ▁ " ) NEW_LINE i = i + 1 NEW_LINE DEDENT print ( current . data , end = " " ) NEW_LINE current = current . next NEW_LINE j = j + 1 NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref ; NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT i = 0 NEW_LINE temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = " ▁ " ) NEW_LINE temp = temp . next NEW_LINE i = i + 1 NEW_LINE DEDENT return i NEW_LINE DEDENT head = None NEW_LINE head = push ( head , 1 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 3 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 6 ) NEW_LINE print ( " Given ▁ linked ▁ list : " ) NEW_LINE n = printList ( head ) NEW_LINE print ( " Reversed Linked list : " ) NEW_LINE printReverse ( head , n ) NEW_LINE print ( ) NEW_LINE