Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Print the alternate nodes of linked list (Iterative Method)
Next article icon

An interesting method to print reverse of a linked list

Last Updated : 26 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 blank space and then print 1st element then “r”, further 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++




#include <iostream>
#include <cstring>
 
using namespace std;
 
// Represents node of a linked list
class Node {
public:
    int data;
    Node* next;
    Node(int val)
    {
        data = val;
        next = nullptr;
    }
};
 
void printReverse(Node* head)
{
    if (!head)
        return;
 
    printReverse(head->next);
 
    cout << head->data << " ";
}
 
Node* push(Node* head, int data)
{
    Node* new_node = new Node(data);
    new_node->next = head;
    head = new_node;
 
    return head;
}
 
int printList(Node* head)
{
    // i for finding the length of the list
    int i = 0;
    Node* temp = head;
    while (temp != nullptr) {
        cout << temp->data << " ";
        temp = temp->next;
        i++;
    }
 
    return i;
}
 
// Driver code
int main()
{
    /* Start with the empty list */
    Node* head = nullptr;
 
    // 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);
 
    cout << "Given linked list: " << endl;
    // printlist print the list and
    // return the size of the list
    int n = printList(head);
 
    // print reverse list
    cout << "\nReversed Linked list: " << endl;
    printReverse(head);
    cout << endl;
 
    return 0;
}
 
 

C




#include <stdio.h>
#include <stdlib.h>
 
// Represents node of a linked list
struct Node {
    int data;
    struct Node* next;
};
 
void printReverse(struct Node* head) {
    if (!head)
        return;
 
    printReverse(head->next);
 
    printf("%d ", head->data);
}
 
struct Node* push(struct Node* head, int data) {
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = data;
    new_node->next = head;
    head = new_node;
 
    return head;
}
 
int printList(struct Node* head) {
    // i for finding the length of the list
    int i = 0;
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
        i++;
    }
 
    return i;
}
 
// Driver code
int main() {
    /* Start with the empty list */
    struct 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);
 
    printf("Given linked list:\n");
    // printlist print the list and
    // return the size of the list
    int n = printList(head);
 
    // print reverse list
    printf("\nReversed Linked list:\n");
    printReverse(head);
    printf("\n");
 
    return 0;
}
 
 

Java




class Node {
    int data;
    Node next;
 
    Node(int val) {
        data = val;
        next = null;
    }
}
 
public class ReversePrint {
    static void printReverse(Node head) {
        if (head == null)
            return;
 
        printReverse(head.next);
 
        System.out.print(head.data + " ");
    }
 
    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) {
        /* 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 the list
        int n = printList(head);
 
        // print reverse list
        System.out.println("\nReversed Linked list:");
        printReverse(head);
        System.out.println();
    }
}
 
 

Python3




class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
 
def print_reverse(head):
    if not head:
        return
 
    print_reverse(head.next)
    print(head.data, end=" ")
 
def push(head, data):
    new_node = Node(data)
    new_node.next = head
    head = new_node
    return head
 
def print_list(head):
    i = 0
    temp = head
    while temp is not None:
        print(temp.data, end=" ")
        temp = temp.next
        i += 1
    return i
 
# Driver code
if __name__ == "__main__":
    # Start with the empty list
    head = None
 
    # 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)
 
    print("Given linked list:")
    # printlist print the list and
    # return the size of the list
    n = print_list(head)
 
    # print reverse list
    print("\nReversed Linked list:")
    print_reverse(head)
    print()
 
 

C#




using System;
 
// Represents node of a linked list
public class Node {
    public int data;
    public Node next;
 
    public Node(int val) {
        data = val;
        next = null;
    }
}
 
public class ReversePrint {
    static void PrintReverse(Node head) {
        if (head == null)
            return;
 
        PrintReverse(head.next);
 
        Console.Write(head.data + " ");
    }
 
    static Node Push(Node head, int data) {
        Node new_node = new Node(data);
        new_node.next = head;
        head = new_node;
 
        return head;
    }
 
    static void PrintList(Node head) {
        Node temp = head;
        while (temp != null) {
            Console.Write(temp.data + " ");
            temp = temp.next;
        }
    }
 
    public static void Main() {
        /* 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 prints the list
        PrintList(head);
 
        // print reverse list
        Console.WriteLine("\nReversed Linked list:");
        PrintReverse(head);
        Console.WriteLine();
    }
}
 
 

Javascript




class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
 
function printReverse(head) {
    if (head === null)
        return;
 
    printReverse(head.next);
 
    console.log(head.data + " ");
}
 
function push(head, data) {
    let new_node = new Node(data);
    new_node.next = head;
    head = new_node;
 
    return head;
}
 
function printList(head) {
    let temp = head;
    while (temp !== null) {
        console.log(temp.data + " ");
        temp = temp.next;
    }
}
 
// Driver code
let 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.log("Given linked list:");
// printlist prints the list
printList(head);
 
// print reverse list
console.log("\nReversed Linked list:");
printReverse(head);
console.log();
 
 

Output: 

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

Time Complexity: O(N).
Auxiliary Space: O(1), 

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 compilers because they do not support anything like carriage return on their console.
Reference : 
StackOverflow/Carriage return


 



Next Article
Print the alternate nodes of linked list (Iterative Method)
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Linked List
Practice Tags :
  • Linked List

Similar Reads

  • Iteratively Reverse a linked list using only 2 pointers (An Interesting Method)
    Given pointer to the head node of a linked list, the task is to reverse the linked list. Examples: Input : Head of following linked list 1->2->3->4->NULL Output : Linked list should be changed to, 4->3->2->1->NULL Input : Head of following linked list 1->2->3->4->
    13 min read
  • Print reverse of a Linked List without extra space and modifications
    Given a Linked List, display the linked list in reverse without using recursion, stack or modifications to given list. Examples: Input: 1->2->3->4->5->NULLOutput: 5 4 3 2 1 Input: 10->5->15->20->24->NULLOutput: 24 20 15 5 10 Below are different solutions that are now al
    7 min read
  • Print the alternate nodes of linked list (Iterative Method)
    Given a linked list, print the alternate nodes of the linked list. Examples: Input : 1 -> 8 -> 3 -> 10 -> 17 -> 22 -> 29 -> 42 Output : 1 -> 3 -> 17 -> 29 Alternate nodes : 1 -> 3 -> 17 -> 29 Input : 10 -> 17 -> 33 -> 38 -> 73 Output : 10 -> 33 -
    9 min read
  • Can we reverse a linked list in less than O(n)?
    It is not possible to reverse a simple singly linked list in less than O(n). A simple singly linked list can only be reversed in O(n) time using recursive and iterative methods. A doubly linked list with head and tail pointers while only requiring swapping the head and tail pointers which require le
    1 min read
  • Print alternate nodes of a linked list using recursion
    Given a linked list, print alternate nodes of this linked list. Examples : Input : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 Output : 1 -> 3 -> 5 -> 7 -> 9 Input : 10 -> 9 Output : 10 Recursive Approach : Initialize a static variable(say flag) If flag
    6 min read
  • Print Doubly Linked list in Reverse Order
    Given a doubly-linked list of positive integers. The task is to print the given doubly linked list data in reverse order. Examples: Input: List = 1 <=> 2 <=> 3 <=> 4 <=> 5 Output: 5 4 3 2 1 Input: 10 <=> 20 <=> 30 <=> 40 Output: 40 30 20 10 Approach: Take a
    7 min read
  • Add number and its reverse represented by Linked List
    Given a number represented by a linked list, write a function that returns the sum of that number with its reverse form, and returns the resultant linked list. Note: Avoid modifying the original linked list. Examples: Input: 1->2->3->4 Output: 5->5->5->5Explanation: Input list: 1 2
    12 min read
  • Print the last k nodes of the linked list in reverse order | Iterative Approaches
    Given a linked list containing N nodes and a positive integer K where K should be less than or equal to N. The task is to print the last K nodes of the list in reverse order. Examples: Input : list: 1->2->3->4->5, K = 2 Output : 5 4 Input : list: 3->10->6->9->12->2->8,
    15+ min read
  • Reverse the order of all nodes at even position in given Linked List
    Given a linked list A[] of N integers, the task is to reverse the order of all integers at an even position. Examples: Input: A[] = 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: 1 6 3 4 5 2Explanation: Nodes at even position in the given linked list are 2, 4 and 6. So, after reversing
    10 min read
  • Print nodes of linked list at given indexes
    Given head of two singly linked lists, first one is sorted and the other one is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the first linked list. For example, if the first linked list is 1->2->5, then you have to p
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences