Print reverse of a Linked List without extra space and modifications
Last Updated :
29 Mar, 2024
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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read