An interesting method to print reverse of a linked list

We are given a linked list, we need to print the linked list in reverse order.

Examples:

Input : list : 5-> 15-> 20-> 25 
Output : Reversed Linked list : 25-> 20-> 15-> 5

Input : list : 85-> 15-> 4-> 20 
Output : Reversed Linked list : 20-> 4-> 15-> 85

Input : list : 85
Output : Reversed Linked list : 85

For printing a list in reverse order, we have already discussed Iterative and Recursive Methods to Reverse.

In this post, an interesting method is discussed, that doesn’t require recursion and does no modifications to list. The function also visits every node of linked list only once.

Trick : Idea behind printing a list in reverse order without any recursive function or loop is to use Carriage return (“r”). For this, we should have knowledge of length of list. Now, we should print n-1 blanck space and then print 1st element then “r”, futher again n-2 blank space and 2nd node then “r” and so on..
Carriage return (“r”) : It commands a printer (cursor or the display of a system console), to move the position of the cursor to the first position on the same line.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to print reverse of list
#include <stdio.h>
#include <stdlib.h>
  
/* Link list node */
struct Node {
    int data;
    struct Node* next;
};
  
/* Function to reverse the linked list */
void printReverse(struct Node** head_ref, int n)
{
    int j = 0;
    struct Node* current = *head_ref;
    while (current != NULL) {
  
        // For each node, print proper number
        // of spaces before printing it
        for (int i = 0; i < 2 * (n - j); i++)
            printf(" ");
  
        // use of carriage return to move back
        // and print.
        printf("%d\r", current->data);
  
        current = current->next;
        j++;
    }
}
  
/* Function to push a node */
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;
}
  
/* Function to print linked list and find its
   length */
int printList(struct Node* head)
{
    // i for finding length of list
    int i = 0;
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d  ", temp->data);
        temp = temp->next;
        i++;
    }
    return i;
}
  
/* Driver program to test above function*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
    // list nodes are as 6 5 4 3 2 1
    push(&head, 1);
    push(&head, 2);
    push(&head, 3);
    push(&head, 4);
    push(&head, 5);
    push(&head, 6);
  
    printf("Given linked list:n");
    // printlist print the list and
    // return the size of list
    int n = printList(head);
  
    // print reverse list with help
    // of carriage return function
    printf("nReversed Linked list:n");
    printReverse(&head, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to print reverse of list
using System;
   
// Represents node of a linkedlist
public class Node {
      public int data;
      public Node next;
      public Node(int val)
      {
          data = val;
          next = null;
      }
}
   
public class GFG {
   
       /* Function to reverse the linked list */
       static void printReverse(Node head, int n)
       {
              int j = 0;
              Node current = head;
              while (current != null) {
                  
                 // For each node, print proper number 
                 // of spaces before printing it 
                 for (int i = 0; i < 2 * (n - j); i++)
                      Console.Write(" ");
   
                 // use of carriage return to move back 
                 // and print.
                 Console.Write("\r" + current.data);
   
                 current = current.next;
                 j++; 
              }
       }
   
       /* Function to push a node */
       static Node push(Node head, int data) 
       {
              Node new_node = new Node(data);
              new_node.next = head;
              head = new_node;
   
              return head;
       }
   
       /* Function to print linked list and find its 
       length */
       static int printList(Node head)
       {
              // i for finding length of list 
              int i = 0;
              Node temp = head;
              while (temp != null)
              {
                     Console.Write(temp.data + " ");
                     temp = temp.next;
                     i++;
              }
   
              return i;
       }
   
       // Driver code
       public static void Main(String []args)
       {
              /* Start with the empty list */
              Node head = null;
   
              // list nodes are as 6 5 4 3 2 1
              head = push(head, 1);
              head = push(head, 2);
              head = push(head, 3);
              head = push(head, 4);
              head = push(head, 5);
              head = push(head, 6);
   
              Console.WriteLine("Given linked list: ");
              // printlist print the list and 
              // return the size of list 
              int n = printList(head); 
     
              // print reverse list with help 
              // of carriage return function
              Console.WriteLine("Reversed Linked list: ");
              printReverse(head, n); 
    
       }
}
   
//contributed by Arnab Kundu

chevron_right


Output:

Given linked list:
6 5 4 3 2 1
Reversed Linked List:
1 2 3 4 5 6

Input and Output Illustration :
Input : 6 5 4 3 2 1
1st Iteration _ _ _ _ _ 6
2nd Iteration _ _ _ _ 5 6
3rd Iteration _ _ _ 4 5 6
4th Iteration _ _ 3 4 5 6
5th Iteration _ 2 3 4 5 6
Final Output 1 2 3 4 5 6

NOTE:Above program may not work on online compiler because they do not support anything like carriage return on their console.


Reference :

stackoverflow/Carriage return

This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : rachana soma, andrew1234



Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.