An interesting method to print reverse of a linked list in C++


A linked list is a data structure that stores data elements in linked form. Each node of the linked list has a data element and a link.

Print reverse of a linked list is a common problem that needs to be addressed in problem solving. So, here we will learn an interesting way to print reverse of a linked list in c++ programming language.

Generally print a reverse linked list needs modifications in the list or multiple traversing of the list but this method does not require any such things and also traverses the linked list only once.

The logic of this method is to use carriage return to print the string in reverse. Carriage return is a command to the printer (cursor in case of display) to leave positions on the line and move to a specific location in one the screen. Now, the logic is to advance the n (the length of the list) leaving space for t ehe elements of the list to be printed. There should be n -1 spaces left before the first element to be printed. then n-2 for the second and so on.

Now let's see a program to illustrate the concept,

Example

 Live Demo

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void printReverse(struct Node** head_ref, int n) ;
void push(struct Node** head_ref, int new_data) ;
int printList(struct Node* head) ;
int main(){
   struct Node* head = NULL;
   push(&head, 2);
   push(&head, 7);
   push(&head, 3);
   push(&head, 5);
   push(&head, 4);
   push(&head, 6);
   printf("Given linked list:\n");
   int n = printList(head);
   printf("\nReversed Linked list:\n");
   printReverse(&head, n);
   return 0;
}
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++)
         cout<<" ";
      cout<<current->data<<"\r";
      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;
}

Output

Given linked list:
6 4 5 3 7 2
Reversed Linked list:
2 7 3 5 4 6

Updated on: 24-Oct-2019

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements