An interesting method to print reverse of a linked list | C program to print reverse of 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 ; Driver program to test above function ; 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
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; void printReverse ( struct Node * * head_ref , int n ) { int j = 0 ; struct Node * current = * head_ref ; while ( current != NULL ) { for ( int i = 0 ; i < 2 * ( n - j ) ; i ++ ) printf ( " ▁ " ) ; printf ( " % d \r " , current -> data ) ; current = current -> next ; j ++ ; } } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int printList ( struct Node * head ) { int i = 0 ; struct Node * temp = head ; while ( temp != NULL ) { printf ( " % d ▁ " , temp -> data ) ; temp = temp -> next ; i ++ ; } return i ; } int main ( ) { struct Node * head = NULL ; push ( & head , 1 ) ; push ( & head , 2 ) ; push ( & head , 3 ) ; push ( & head , 4 ) ; push ( & head , 5 ) ; push ( & head , 6 ) ; printf ( " Given ▁ linked ▁ list : STRNEWLINE " ) ; int n = printList ( head ) ; printf ( " Reversed Linked list : " printReverse ( & head , n ) ; printf ( " STRNEWLINE " ) ; return 0 ; }