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:
An interesting method to print reverse of a linked list
Next article icon

Print reverse of a Linked List without extra space and modifications

Last Updated : 29 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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->NULL
Output: 5 4 3 2 1

Input: 10->5->15->20->24->NULL
Output: 24 20 15 5 10

Below are different solutions that are now allowed here as we cannot use extra space and modify list.
1) Recursive solution to print reverse a linked list. Requires extra space.
2) Reverse linked list and then print. This requires modifications to original list. 
3) Stack based solution to print linked list reverse. Push all nodes one by one to a stack. Then one by one pop elements from stack and print. This also requires extra space.
Algorithms:

1) Find n = count nodes in linked list.  2) For i = n to 1, do following.      Print i-th node using get n-th node function

C++




// C/C++ program to print reverse of linked list
// without extra space and without modifications.
#include<stdio.h>
#include<stdlib.h>
  
/* Link list node */
struct Node
{
    int data;
    struct Node* next;
};
  
/* Given a reference (pointer to pointer) to the head
  of a list and an int, push a new node on the front
  of the list. */
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;
}
  
/* Counts no. of nodes in linked list */
int getCount(struct Node* head)
{
    int count = 0;  // Initialize count
    struct Node* current = head;  // Initialize current
    while (current != NULL)
    {
        count++;
        current = current->next;
    }
    return count;
}
  
/* Takes head pointer of the linked list and index
    as arguments and return data at index*/
int getNth(struct Node* head, int n)
{
    struct Node* curr = head;
    for (int i=0; i<n-1 && curr != NULL; i++)
       curr = curr->next;
    return curr->data;
}
  
void printReverse(Node *head)
{
    // Count nodes
    int n = getCount(head);
  
    for (int i=n; i>=1; i--)
        printf("%d ", getNth(head, i));
}
  
/* Driver program to test count function*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
  
    /* Use push() to construct below list
     1->2->3->4->5 */
    push(&head, 5);
    push(&head, 4);
    push(&head, 3);
    push(&head, 2);
    push(&head, 1);
  
    printReverse(head);
  
    return 0;
}
 
 

Java




// Java program to print reverse of linked list
// without extra space and without modifications.
class GFG 
{
      
/* Link list node */
static class Node
{
    int data;
    Node next;
};
static Node head;
  
/* Given a reference (pointer to pointer) to 
the head of a list and an int, push a new node 
on the front of the list. */
static void push(Node head_ref, int new_data)
{
    Node new_node = new Node();
    new_node.data = new_data;
    new_node.next = (head_ref);
    (head_ref) = new_node;
    head = head_ref;
}
  
/* Counts no. of nodes in linked list */
static int getCount(Node head)
{
    int count = 0; // Initialize count
    Node current = head; // Initialize current
    while (current != null)
    {
        count++;
        current = current.next;
    }
    return count;
}
  
/* Takes head pointer of the linked list and 
index as arguments and return data at index*/
static int getNth(Node head, int n)
{
    Node curr = head;
    for (int i = 0; i < n - 1 && curr != null; i++)
    curr = curr.next;
    return curr.data;
}
  
static void printReverse()
{
    // Count nodes
    int n = getCount(head);
  
    for (int i = n; i >= 1; i--)
        System.out.printf("%d ", getNth(head, i));
}
  
// Driver Code
public static void main(String[] args)
{
    /* Start with the empty list */
    head = null;
  
    /* Use push() to construct below list
    1->2->3->4->5 */
    push(head, 5);
    push(head, 4);
    push(head, 3);
    push(head, 2);
    push(head, 1);
  
    printReverse();
}
}
  
// This code is contributed by PrinciRaj1992 
 
 

Python3




# Python3 program to print reverse of linked list
# without extra space and without modifications.
   
''' Link list node '''
class Node:
      
    def __init__(self, data):
        self.data = data
        self.next = None
       
''' Given a reference (pointer to pointer) to the head
  of a list and an int, push a new node on the front
  of the list. '''
def push( head_ref, new_data):    
    new_node = Node(new_data)
    new_node.next = head_ref;
    head_ref = new_node;
    return head_ref
  
''' Counts no. of nodes in linked list '''
def getCount(head):
    count = 0;  # Initialize count
    current = head;  # Initialize current    
    while (current != None):    
        count += 1
        current = current.next;    
    return count;
   
''' Takes head pointer of the linked list and index
    as arguments and return data at index'''
def getNth(head, n):
    curr = head;   
    i = 0    
    while i < n - 1 and curr != None:
        curr = curr.next; 
        i += 1    
    return curr.data;
   
def printReverse(head):
  
    # Count nodes
    n = getCount(head);
      
    for i in range(n, 0, -1):
        print(getNth(head, i), end = ' ');
       
# Driver code
if __name__=='__main__':
      
    ''' Start with the empty list '''
    head = None;
   
    ''' Use push() to construct below list
     1.2.3.4.5 '''
    head = push(head, 5);
    head = push(head, 4);
    head = push(head, 3);
    head = push(head, 2);
    head = push(head, 1);
   
    printReverse(head);
       
# This code is contributed by rutvik_56
 
 

C#




// C# program to print reverse of 
// linked list without extra space
// and without modifications.
using System;
      
class GFG 
{
      
/* Link list node */
public class Node
{
    public int data;
    public Node next;
};
static Node head;
  
/* Given a reference (pointer to pointer) 
to the head of a list and an int, push a 
new node on the front of the list. */
static void push(Node head_ref, 
                 int new_data)
{
    Node new_node = new Node();
    new_node.data = new_data;
    new_node.next = (head_ref);
    (head_ref) = new_node;
    head = head_ref;
}
  
/* Counts no. of nodes in linked list */
static int getCount(Node head)
{
    int count = 0; // Initialize count
    Node current = head; // Initialize current
    while (current != null)
    {
        count++;
        current = current.next;
    }
    return count;
}
  
/* Takes head pointer of the linked list and 
index as arguments and return data at index*/
static int getNth(Node head, int n)
{
    Node curr = head;
    for (int i = 0; 
             i < n - 1 && curr != null; i++)
    curr = curr.next;
    return curr.data;
}
  
static void printReverse()
{
    // Count nodes
    int n = getCount(head);
  
    for (int i = n; i >= 1; i--)
        Console.Write("{0} ", getNth(head, i));
}
  
// Driver Code
public static void Main(String[] args)
{
    /* Start with the empty list */
    head = null;
  
    /* Use push() to construct below list
    1->2->3->4->5 */
    push(head, 5);
    push(head, 4);
    push(head, 3);
    push(head, 2);
    push(head, 1);
  
    printReverse();
}
}
  
// This code is contributed by Princi Singh
 
 

Javascript




<script>
  
// JavaScript program to implement above approach
  
  
//  Link list node 
class Node{
      
    constructor(data){
        this.data = data
        this.next = null
    }
}
      
// Given a reference (pointer to pointer) to the head
// of a list and an int, push a new node on the front
// of the list.
  
function push( head_ref, new_data){
    let new_node = new Node(new_data)
    new_node.next = head_ref;
    head_ref = new_node;
    return head_ref
}
  
// Counts no. of nodes in linked list
  
function getCount(head){
    let count = 0; // Initialize count
    let current = head; // Initialize current
    while (current != null){
        count += 1
        current = current.next;
    }
    return count;
}
  
// Takes head pointer of the linked list and index
//     as arguments and return data at index
  
function getNth(head, n){
    let curr = head;
    let i = 0
    while(i < n - 1 && curr != null){
        curr = curr.next;
        i += 1
    }
    return curr.data;
}
  
function printReverse(head){
  
    // Count nodes
    let n = getCount(head);
      
    for(let i=n;i>0;i--)
        document.write(getNth(head, i),' ');
}
      
// Driver code
      
// Start with the empty list
let head = null;
  
//  Use push() to construct below list
// 1.2.3.4.5 
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
  
printReverse(head);
  
  
// This code is contributed by shinjanpatra
  
</script>
 
 

Output: 
 

5 4 3 2 1

Time complexity: O(n2) where n is the number of nodes in the given linked list
Auxiliary Space: O(1), as constant extra space is required.



Next Article
An interesting method to print reverse of a linked list

S

Shahnawaz_Ali
Improve
Article Tags :
  • DSA
  • Linked List
  • programming-puzzle
Practice Tags :
  • Linked List

Similar Reads

  • 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-> 5Input : list : 85-> 15-> 4-> 20 Output : Reversed Linked list : 20-> 4-> 15-> 85Input : list : 8
    7 min read
  • Print reverse of a Linked List without actually reversing
    Given a singly linked list. The task is to print the linked list in reverse order without actually reversing the linked list. Examples: Input: head : 1 -> 2 -> 3 -> 4 -> NULL Output: 4 -> 3 -> 2 -> 1 -> NULL Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 5
    8 min read
  • Reverse nodes of a linked list without affecting the special characters
    Given a linked list of alphabets and special characters. Reverse the given linked list without affecting the position of the special characters. Examples: Input: g -> @ -> e -> # -> e -> $ -> k -> s -> NULL Output: s -> @ -> k -> # -> e -> $ -> e -> g -
    12 min read
  • Add two numbers represented by Linked List without any extra space
    Given two numbers represented by two linked lists, write a function that returns sum list. The sum list is linked list representation of addition of two input numbers. Expected Space Complexity O(1). Examples: Input: L1 = 5 -> 6 -> 3 -> NULL L2 = 8 -> 4 -> 2 -> NULL Output: 1 ->
    11 min read
  • Clone a linked list with next and random pointer in O(1) space
    Given a linked list of size N where each node has two links: next pointer pointing to the next node and random pointer to any random node in the list. The task is to create a clone of this linked list in O(1) space, i.e., without any extra space.  Examples:  Input: Head of the below linked list Outp
    10 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
  • Reverse a Doubly Linked List without swapping nodes
    Write a program to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Approach: In the previous post, doubly linked list is being reversed by swapping prev and next pointers for all nodes, changing prev of the head (o
    10 min read
  • Swap given nodes in a Doubly Linked List without modifying data
    Given a doubly linked list having all unique elements and two keys X and Y, the task is to swap nodes for two given keys by changing links only. Note: It may be considered that X and Y are always present in the list. Examples: Input: list = 1 <-> 8 <-> 7 <-> 9 <-> 4, X = 1, Y
    11 min read
  • Print Reverse a linked list using Stack
    Given a linked list, print the reverse of it without modifying the list. Examples: Input : 1 2 3 4 5 6 Output : 6 5 4 3 2 1 Input : 12 23 34 45 56 67 78 Output : 78 67 56 45 34 23 12 Below are different solutions that are now allowed here as we cannot use extra space and modify the list. Recursive s
    9 min read
  • Reverse a stack without using extra space in O(n)
    Reverse a Stack without using recursion and extra space. Even the functional Stack is not allowed. Examples: Input : 1->2->3->4 Output : 4->3->2->1 Input : 6->5->4 Output : 4->5->6 We have discussed a way of reversing a stack in the below post.Reverse a Stack using Recu
    6 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