Print Reverse a linked list using Stack
Last Updated :
06 Jan, 2023
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 solution to print reverse a linked list. Requires extra space.
- Reverse linked list and then print. This requires modifications to the original list.
- A O(n2) solution to print reverse of linked list that first count nodes and then prints k-th node from the end.
In this post, the efficient stack-based solution is discussed.
- First, insert all the elements in the stack
- Print stack till stack is not empty
Note: Instead of inserting data from each node into the stack, insert the node's address onto the stack. This is because the size of the node's data will be generally more than the size of the node's address. Thus, the stack would end up requiring more memory if it directly stored the data elements. Also, we cannot insert the node's data onto the stack if each node contained more than one data member. Hence, a simpler and efficient solution would be to simply insert the node's address.
Below is the implementation of the above idea:
C++
// C/C++ program to print reverse of linked list
// using stack.
#include <bits/stdc++.h>
using namespace std;
// 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)
{
// store Node addresses in stack
stack<Node*> stk;
Node* ptr = head;
while (ptr != NULL) {
stk.push(ptr);
ptr = ptr->next;
}
// print data from stack
while (!stk.empty()) {
cout << stk.top()->data << " ";
stk.pop(); // pop after print
}
cout << "\n";
}
// Driver code
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);
// Function call
printReverse(head);
return 0;
}
Java
// Java program to print reverse of linked list
// using stack.
import java.util.*;
class GFG {
/* Link list node */
static class Node {
int data;
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. */
static Node 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;
return 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(Node head)
{
// store Node addresses in stack
Stack<Node> stk = new Stack<Node>();
Node ptr = head;
while (ptr != null) {
stk.push(ptr);
ptr = ptr.next;
}
// print data from stack
while (stk.size() > 0) {
System.out.print(stk.peek().data + " ");
stk.pop(); // pop after print
}
System.out.println("\n");
}
// Driver code
public static void main(String args[])
{
// Start with the empty list
Node 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);
// Function call
printReverse(head);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 program to print reverse of linked list
# using stack.
# Node of a linked list
class Node:
def __init__(self, next=None, data=None):
self.next = next
self.data = data
# 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_node.data = 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 = 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 = i + 1
return curr.data
def printReverse(head):
# store Node addresses in stack
stk = []
ptr = head
while (ptr != None):
stk.append(ptr)
ptr = ptr.next
# print data from stack
while (len(stk) > 0):
print(stk[-1].data, end=" ")
stk.pop() # pop after print
print(" ")
# Driver code
# 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)
# Function call
printReverse(head)
# This code is Contributed by Arnab Kundu
C#
// C# program to print reverse of linked list
// using stack.
using System;
using System.Collections.Generic;
class GFG {
/* Link list node */
public class Node {
public int data;
public 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. */
static Node 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;
return 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(Node head)
{
// store Node addresses in stack
Stack<Node> stk = new Stack<Node>();
Node ptr = head;
while (ptr != null) {
stk.Push(ptr);
ptr = ptr.next;
}
// print data from stack
while (stk.Count > 0) {
Console.Write(stk.Peek().data + " ");
stk.Pop(); // pop after print
}
Console.WriteLine("\n");
}
// Driver code
public static void Main(String[] args)
{
// Start with the empty list
Node 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);
// Function call
printReverse(head);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to print reverse of linked list
// using stack.
/* Link list node */
class Node {
constructor()
{
this.data = 0;
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)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
/* Counts no. of nodes in linked list */
function getCount(head)
{
var count = 0; // Initialize count
var 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*/
function getNth(head, n)
{
var curr = head;
for (var i = 0; i < n - 1 && curr != null; i++)
curr = curr.next;
return curr.data;
}
function printReverse(head)
{
// store Node addresses in stack
var stk = [];
var ptr = head;
while (ptr != null) {
stk.push(ptr);
ptr = ptr.next;
}
// print data from stack
while (stk.length > 0) {
document.write(stk[stk.length-1].data + " ");
stk.pop(); // pop after print
}
document.write("<br>");
}
// Driver code
// Start with the empty list
var 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);
// Function call
printReverse(head);
</script>
Time complexity: O(N) where N is number of nodes of linked list
Auxiliary Space: O(n)
Similar Reads
Reverse a linked list using recursion Given a linked list, the task is to reverse the linked list by changing the links between nodes.Examples: Input: Linked List = 1 -> 2 -> 3 -> 4 -> NULL Output: 4 -> 3 -> 2 -> 1 -> NULLInput: Linked List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 5 -> 4 -> 3
6 min read
Reverse a Doubly linked list using recursion Given a doubly linked list. Reverse it using recursion. Original Doubly linked list Reversed Doubly linked list We have discussed Iterative solution to reverse a Doubly Linked List Algorithm: If list is empty, return Reverse head by swapping head->prev and head->next If prev = NULL it means th
9 min read
Reverse a sublist of linked list Given a linked list and positions m and n. We need to reverse the linked list from position m to n.Examples: Input : linkedlist : 10->20->30->40->50->60->70->NULL , m = 3 and n = 6Output : 10->20->60->50->40->30->70->NULLExplanation: Linkedlist reversed star
15+ min read
Python | Stack using Doubly Linked List A stack is a collection of objects that are inserted and removed using Last in First out Principle(LIFO). User can insert elements into the stack, and can only access or remove the recently inserted object on top of the stack. The main advantage of using LinkedList over array for implementing stack
4 min read
Reverse a Linked List in groups of given size using Stack Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed.Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
8 min read
Reverse a Linked List Given a linked list, the task is to reverse the linked list by changing the links between nodes.Examples: Input: head: 1 -> 2 -> 3 -> 4 -> NULLOutput: head: 4 -> 3 -> 2 -> 1 -> NULLExplanation: Reversed Linked List: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULLOut
15+ min read
Reverse a Stack using Queue Given a stack, the task is to reverse the stack using the queue data structure. Examples: Input: Stack: (Top to Bottom) [10 -> 20 -> 30 -> 40]Output: Stack: (Top to Bottom) [40 -> 30 -> 20 -> 10] Input: Stack: [6 -> 5 -> 4]Output: Stack: [4 -> 5 -> 6] Approach: The prob
5 min read
Implement a stack using singly linked list To implement a stack using a singly linked list, we need to ensure that all operations follow the LIFO (Last In, First Out) principle. This means that the most recently added element is always the first one to be removed. In this approach, we use a singly linked list, where each node contains data a
13 min read
How to Reverse a Stack using Recursion Write a program to reverse a stack using recursion, without using any loop.Example: Input: elements present in stack from top to bottom 4 3 2 1Output: 1 2 3 4Input: elements present in stack from top to bottom 1 2 3Output: 3 2 1The idea of the solution is to hold all values in Function Call Stack un
4 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 -> NULLInput: head: 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 5 -
8 min read