The Wayback Machine - https://web.archive.org/web/20240926113858/https://www.geeksforgeeks.org/reverse-stack-without-using-extra-space/
Open In App

Reverse a stack without using extra space in O(n)

Last Updated : 10 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 Recursion

The above solution requires O(n) extra space. We can reverse a stack in O(1) time if we internally represent the stack as a linked list. Reverse a stack would require a reversing of a linked list which can be done with O(n) time and O(1) extra space.
Note that push() and pop() operations still take O(1) time.  

Implementation:

C++




// C++ program to implement Stack 
// using linked list so that reverse
// can be done with O(1) extra space.
#include<bits/stdc++.h>
using namespace std;
  
class StackNode {
    public:
    int data;
    StackNode *next;
      
    StackNode(int data)
    {
        this->data = data;
        this->next = NULL;
    }
};
  
class Stack {
      
    StackNode *top;
      
    public:
      
    // Push and pop operations
    void push(int data)
    {
        if (top == NULL) {
            top = new StackNode(data);
            return;
        }
        StackNode *s = new StackNode(data);
        s->next = top;
        top = s;
    }
      
    StackNode* pop()
    {
        StackNode *s = top;
        top = top->next;
        return s;
    }
  
    // prints contents of stack
    void display()
    {
        StackNode *s = top;
        while (s != NULL) {
            cout << s->data << " ";
            s = s->next;
        }
        cout << endl;
    }
  
    // Reverses the stack using simple
    // linked list reversal logic.
    void reverse()
    {
        StackNode *prev, *cur, *succ;
        cur = prev = top;
        cur = cur->next;
        prev->next = NULL;
        while (cur != NULL) {
  
            succ = cur->next;
            cur->next = prev;
            prev = cur;
            cur = succ;
        }
        top = prev;
    }
};
  
// driver code
int main()
{
    Stack *s = new Stack();
    s->push(1);
    s->push(2);
    s->push(3);
    s->push(4);
    cout << "Original Stack" << endl;;
    s->display();
    cout << endl;
      
    // reverse
    s->reverse();
  
    cout << "Reversed Stack" << endl;
    s->display();
      
    return 0;
}
// This code is contributed by Chhavi.


Java




// Java program to implement Stack using linked
// list so that reverse can be done with O(1) 
// extra space.
class StackNode {
    int data;
    StackNode next;
    public StackNode(int data)
    {
        this.data = data;
        this.next = null;
    }
}
  
class Stack {
    StackNode top;
  
    // Push and pop operations
    public void push(int data)
    {
        if (this.top == null) {
            top = new StackNode(data);
            return;
        }
        StackNode s = new StackNode(data);
        s.next = this.top;
        this.top = s;
    }
    public StackNode pop()
    {
        StackNode s = this.top;
        this.top = this.top.next;
        return s;
    }
  
    // prints contents of stack
    public void display()
    {
        StackNode s = this.top;
        while (s != null) {
            System.out.print(s.data + " ");
            s = s.next;
        }
        System.out.println();
    }
  
    // Reverses the stack using simple
    // linked list reversal logic.
    public void reverse()
    {
        StackNode prev, cur, succ;
        cur = prev = this.top;
        cur = cur.next;
        prev.next = null;
        while (cur != null) {
  
            succ = cur.next;
            cur.next = prev;
            prev = cur;
            cur = succ;
        }
        this.top = prev;
    }
}
  
public class reverseStackWithoutSpace {
    public static void main(String[] args)
    {
        Stack s = new Stack();
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);
        System.out.println("Original Stack");
        s.display();
  
        // reverse
        s.reverse();
  
        System.out.println("Reversed Stack");
        s.display();
    }
}


Python3




# Python3 program to implement Stack 
# using linked list so that reverse
# can be done with O(1) extra space.
class StackNode:
      
    def __init__(self, data):
          
        self.data = data
        self.next = None
  
class Stack:
      
    def __init__(self):
           
        self.top = None
       
    # Push and pop operations
    def push(self, data):
      
        if (self.top == None):
            self.top = StackNode(data)
            return
          
        s = StackNode(data)
        s.next = self.top
        self.top = s
       
    def pop(self):
      
        s = self.top
        self.top = self.top.next
        return s
   
    # Prints contents of stack
    def display(self):
      
        s = self.top
          
        while (s != None):
            print(s.data, end = ' ')
            s = s.next
          
    # Reverses the stack using simple
    # linked list reversal logic.
    def reverse(self):
  
        prev = self.top
        cur = self.top
        cur = cur.next
        succ = None
        prev.next = None
          
        while (cur != None):
            succ = cur.next
            cur.next = prev
            prev = cur
            cur = succ
          
        self.top = prev
      
# Driver code
if __name__=='__main__':
      
    s = Stack()
    s.push(1)
    s.push(2)
    s.push(3)
    s.push(4)
      
    print("Original Stack")
    s.display()
    print()
       
    # Reverse
    s.reverse()
   
    print("Reversed Stack")
    s.display()
       
# This code is contributed by rutvik_56


C#




// C# program to implement Stack using linked
// list so that reverse can be done with O(1) 
// extra space.
using System; 
  
public class StackNode
{
    public int data;
    public StackNode next;
    public StackNode(int data)
    {
        this.data = data;
        this.next = null;
    }
}
  
public class Stack 
{
    public StackNode top;
  
    // Push and pop operations
    public void push(int data)
    {
        if (this.top == null)
        {
            top = new StackNode(data);
            return;
        }
        StackNode s = new StackNode(data);
        s.next = this.top;
        this.top = s;
    }
      
    public StackNode pop()
    {
        StackNode s = this.top;
        this.top = this.top.next;
        return s;
    }
  
    // prints contents of stack
    public void display()
    {
        StackNode s = this.top;
        while (s != null) 
        {
            Console.Write(s.data + " ");
            s = s.next;
        }
        Console.WriteLine();
    }
  
    // Reverses the stack using simple
    // linked list reversal logic.
    public void reverse()
    {
        StackNode prev, cur, succ;
        cur = prev = this.top;
        cur = cur.next;
        prev.next = null;
        while (cur != null)
        {
            succ = cur.next;
            cur.next = prev;
            prev = cur;
            cur = succ;
        }
        this.top = prev;
    }
}
  
public class reverseStackWithoutSpace 
{
    // Driver code
    public static void Main(String []args)
    {
        Stack s = new Stack();
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);
        Console.WriteLine("Original Stack");
        s.display();
  
        // reverse
        s.reverse();
  
        Console.WriteLine("Reversed Stack");
        s.display();
    }
}
  
// This code is contributed by Arnab Kundu


Javascript




<script>
  
// JavaScript program to implement Stack 
// using linked list so that reverse can 
// be done with O(1) extra space.
class StackNode 
{
    constructor(data) 
    {
        this.data = data;
        this.next = null;
    }
}
  
class Stack 
{
    top = null;
      
    // Push and pop operations
    push(data)
    {
        if (this.top == null) 
        {
            this.top = new StackNode(data);
            return;
        }
        var s = new StackNode(data);
        s.next = this.top;
        this.top = s;
    }
      
    pop() 
    {
        var s = this.top;
        this.top = this.top.next;
        return s;
    }
      
    // Prints contents of stack
    display() 
    {
        var s = this.top;
        while (s != null)
        {
            document.write(s.data + " ");
            s = s.next;
        }
        document.write("<br>");
    }
      
    // Reverses the stack using simple
    // linked list reversal logic.
    reverse() 
    {
        var prev, cur, succ;
        cur = prev = this.top;
        cur = cur.next;
        prev.next = null;
          
        while (cur != null) 
        {
            succ = cur.next;
            cur.next = prev;
            prev = cur;
            cur = succ;
        }
        this.top = prev;
    }
}
  
// Driver code
var s = new Stack();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
document.write("Original Stack <br>");
s.display();
  
// Reverse
s.reverse();
  
document.write("Reversed Stack <br>");
s.display();
  
// This code is contributed by rdtank
  
</script>


Output

Original Stack
4 3 2 1 

Reversed Stack
1 2 3 4 

Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.

 



Previous Article
Next Article

Similar Reads

Clone a stack without using extra space | Set 2
Given a stack S, the task is to copy the content of the given stack S to another stack T maintaining the same order. Examples: Input: Source:- |5| |4| |3| |2| |1|Output: Destination:- |5| |4| |3| |2| |1| Input: Source:- |12| |13| |14| |15| |16|Output: Destination:- |12| |13| |14| |15| |16| Reversing the Stack-Based Approach: Please refer to the pre
7 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-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULLOutput: 5 4 3 2 1 Input: 10-&gt;5-&gt;15-&gt;20-&gt;24-&gt;NULLOutput: 24 20 15 5 10 Below are different solutions that are now allowed here as we cannot use extra space and modify
7 min read
Clone a stack without extra space
Given a source stack, copy the contents of the source stack to the destination stack maintaining the same order without using extra space. Examples: Input : Source:- |3| |2| |1|Output : Destination:- |3| |2| |1|Input : Source:- |a| |b| |c|Output : Destination:- |a| |b| |c|Approach: In order to solve this without using extra space, we first reverse
15 min read
Create Balanced Binary Tree using its Leaf Nodes without using extra space
Prerequisites: Binary Tree to Doubly Linked ListGiven a Binary Tree, the task is to create a Balanced Binary Tree from all the leaf nodes of the given Binary Tree. Examples: Input: Output: 7 8 5 9 10 Explanation: Required balanced binary tree will be: Input: Output: 13 21 29 7 15 Explanation: Required balanced binary tree is: 29 / \ 21 7 / \ 13 15
15 min read
Design a dynamic stack using arrays that supports getMin() in O(1) time and O(1) extra space
Design a special dynamic Stack using an array that supports all the stack operations such as push(), pop(), peek(), isEmpty(), and getMin() operations in constant Time and Space complexities. Examples: Assuming the right to left orientation as the top to bottom orientation and performing the operations: Push(10): 10 is added to the top of the stack
15+ min read
Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space
We have an array of the form {a0, a1, a2....., an, b0, b1, b2, .....bn} and our task is to rearrange the same in theform given below by using O(1) space- {a0, b0, a1, b1, a2, b2...........an, bn} Examples: Input : arr[] = {1, 3, 5, 7, 2, 4, 6, 8} Output : {1, 2, 3, 4, 5, 6, 7, 8} Input : arr[] = {11, 13, 15, 12, 14, 16} Output : {11, 12, 13, 14, 15
11 min read
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Given a square matrix, turn it by 90 degrees in a clockwise direction without using any extra space. Examples: Input: 1 2 3 4 5 6 7 8 9 Output: 7 4 1 8 5 2 9 6 3 Input: 1 2 3 4 Output: 3 1 4 2 Method 1 Approach: The approach is similar to Inplace rotate square matrix by 90 degrees | Set 1. The only thing that is different is to print the elements o
15+ min read
Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space | Set 2
Given an array arr[] consisting of 2* N elements in the form of { a1, a2, â€Ķ, aN, b1, b2, ..., bN }, the task is to shuffle the array to {a1, b1, a2, b2, ..., an, b1} without using extra space. Examples : Input: arr[] = { 1, 3, 5, 2, 4, 6 }Output: 1 2 3 4 5 6Explanation: The output contains the elements in the form of { a1, b1, a2, b2, a3, b3 }. Inp
15 min read
Check if a number is palindrome or not without using any extra space | Set 2
Given a number ‘n’ and our goal is to find out it is palindrome or not without using any extra space. We can’t make a new copy of number. Examples: Input: n = 2332Output: Yes it is Palindrome.Explanation:original number = 2332reversed number = 2332Both are same hence the number is palindrome. Input: n=1111Output: Yes it is Palindrome. Input: n = 12
5 min read
Rotate a matrix by 90 degree without using any extra space | Set 2
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space. Examples: Input: 1 2 3 4 5 6 7 8 9Output: 3 6 9 2 5 8 1 4 7 Rotated the input matrix by90 degrees in anti-clockwise direction.Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13Rotated the input matrix by9
15+ min read
Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ......, an, bn} without using extra space
Given an array of 2n elements in the following format { a1, a2, a3, a4, ....., an, b1, b2, b3, b4, ...., bn }. The task is shuffle the array to {a1, b1, a2, b2, a3, b3, ......, an, bn } without using extra space. Examples: Input : arr[] = { 1, 2, 9, 15 }Output : 1 9 2 15 Input : arr[] = { 1, 2, 3, 4, 5, 6 }Output : 1 4 2 5 3 6 Recommended: Please s
10 min read
To check a number is palindrome or not without using any extra space
Given a number 'n' and our goal is to find out it is palindrome or not without using any extra space. We can't make a new copy of the number . Examples: Input : 2332 Output : Yes it is Palindrome. Explanation: original number = 2332 reversed number = 2332 Both are same hence the number is palindrome. Input :1111 Output :Yes it is Palindrome. Input
6 min read
Shuffle array {a1, a2, .. an, b1, b2, .. bn} as {a1, b1, a2, b2, a3, b3, â€Ķâ€Ķ, an, bn} without using extra space
Given an array of 2n elements in the following format { a1, a2, a3, a4, â€Ķ.., an, b1, b2, b3, b4, â€Ķ., bn }. The task is shuffle the array to {a1, b1, a2, b2, a3, b3, â€Ķâ€Ķ, an, bn } without using extra space.Examples : Input : arr[] = { 1, 2, 9, 15 } Output : 1 9 2 15 Input : arr[] = { 1, 2, 3, 4, 5, 6 } Output : 1 4 2 5 3 6 We have discussed O(n2) and
14 min read
Replace all occurrences of string AB with C without using extra space
Given a string str that may contain one more occurrences of "AB". Replace all occurrences of "AB" with "C" in str. Examples: Input : str = "helloABworld"Output : str = "helloCworld"Input : str = "fghABsdfABysu"Output : str = "fghCsdfCysu"A simple solution is to find all occurrences of "AB". For every occurrence, replace it with C and move all chara
10 min read
Find maximum in a stack in O(1) time and O(1) extra space
Given a stack of integers. The task is to design a special stack such that the maximum element can be found in O(1) time and O(1) extra space. Examples: Given Stack : 2 5 1 64 --&gt; Maximum So Output must be 64 when getMax() is called. Below are the different functions designed to push and pop elements from the stack. Push(x) : Inserts x at the to
11 min read
Design a stack that supports getMin() in O(1) time and O(1) extra space
Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must have a time and space complexity of O(1). Note: To implement SpecialStack, you should only use s
15+ 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 -&gt; 6 -&gt; 3 -&gt; NULL L2 = 8 -&gt; 4 -&gt; 2 -&gt; NULL Output: 1 -&gt; 4 -&gt; 0 -&gt; 5 -&gt; NULL Input: L1 = 1 -&gt;
11 min read
Find pair for given sum in a sorted singly linked without extra space
Given a sorted singly linked list and a value x, the task is to find pair whose sum is equal to x. We are not allowed to use any extra space and expected time complexity is O(n). Examples: Input : head = 3--&gt;6--&gt;7--&gt;8--&gt;9--&gt;10--&gt;11 , x=17Output: (6, 11), (7, 10), (8, 9)Hint : We are allowed to modify original linked list A simple
12 min read
Sorting a Queue without extra space
Given a queue with random elements, we need to sort it. We are not allowed to use extra space. The operations allowed on queue are : enqueue() : Adds an item to rear of queue. In C++ STL queue, this function is called push().dequeue() : Removes an item from front of queue. In C++ STL queue, this function is called pop().isEmpty() : Checks if a queu
9 min read
Find maximum in stack in O(1) without using additional stack in Python
The task is to design a stack which can get the maximum value in the stack in O(1) time without using an additional stack in Python. Examples: Input: Consider the following SpecialStack 16 –&gt; TOP29151918When getMax() is called it should return 29, which is the maximum element in the current stack. If we do pop two times on stack, the stack becom
3 min read
k smallest elements in same order using O(1) extra space
We are given an array of n-elements you have to find k smallest elements from the array but they must be in the same order as they are in the given array and we are allowed to use only O(1) extra space. Examples: Input : arr[] = {4, 2, 6, 1, 5}, k = 3 Output : 4 2 1 Explanation : 1, 2 and 4 are three smallest numbers and 4 2 1 is their order in giv
8 min read
K'th Largest element in BST using constant extra space
Given a binary search tree, task is to find Kth largest element in the binary search tree. Example: Input : k = 3 Root of following BST 10 / \ 4 20 / / \ 2 15 40 Output : 15 The idea is to use Reverse Morris Traversal which is based on Threaded Binary Trees. Threaded binary trees use the NULL pointers to store the successor and predecessor informat
10 min read
Sum of K largest elements in BST using O(1) Extra space
Given a BST, the task is to find the sum of all elements greater than or equal to K-th largest element in O(1) space.Examples: Input : K = 3 8 / \ 7 10 / / \ 2 9 13 Output : 32 Explanation: 3rd largest element is 9 so sum of all elements greater than or equal to 9 are 9 + 10 + 13 = 32. Input : K = 2 8 / \ 5 11 / \ 2 7 \ 3 Output : 19 Explanation: 2
9 min read
Duplicates in an array in O(n) time and by using O(1) extra space | Set-3
Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. It is required that the order in which elements repeat should be maintained. If there is no repeating element present then print -1. Examples: Input :
10 min read
Connect nodes at same level using constant extra space
Write a function to connect all the adjacent nodes at the same level in a binary tree. The structure of the given Binary Tree node is like following C/C++ Code struct node{ int data; struct node* left; struct node* right; struct node* nextRight; }; // This code is contributed by Yash Agarwal(yashagarwal2852002) C/C++ Code struct node { int data; st
15+ min read
K'th smallest element in BST using O(1) Extra Space
Given a Binary Search Tree (BST) and a positive integer k, find the k'th smallest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 10, and if k = 5, then output should be 14. We have discussed two methods in this post and one method in this post. All of the previous methods require extra space. H
13 min read
Print n x n spiral matrix using O(1) extra space
Given a number n, print a n x n spiral matrix (of numbers from 1 to n x n) in clockwise direction using O(1) space. Example : Input: n = 5 Output: 25 24 23 22 21 10 9 8 7 20 11 2 1 6 19 12 3 4 5 18 13 14 15 16 17 We strongly recommend you to minimize your browser and try this yourself first. The solution becomes simple if extra space is allowed. We
9 min read
Length of longest palindrome list in a linked list using O(1) extra space
Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: Input : List = 2-&gt;3-&gt;7-&gt;3-&gt;2-&gt;12-&gt;24 Output : 5 The longest palindrome list is 2-&gt;3-&gt;7-&gt;3-&gt;2 Input : List = 12-&gt;4-&gt;4-&gt;3-&gt;14 Output : 2 The longest palindrome list is 4-&gt;4Recommended PracticeLeng
9 min read
Sort an array according to absolute difference with a given value "using constant extra space"
Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., element having minimum difference comes first and so on, using constant extra space. Note : If two or more elements are at equal distance arrange them in same sequence as in the given array.Examples: Input : arr[] = {10,
7 min read
Sort a binary array using one traversal and no extra space
Given a binary array, sort it using one traversal and no extra space Examples: Input: 1 0 0 1 0 1 0 1 1 1 1 1 1 0 0 1 1 0 1 0 0 Output: 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1Explanation: The output is a sorted array of 0 and 1 Input: 1 0 1 0 1 0 1 0 Output: 0 0 0 0 1 1 1 1Explanation: The output is a sorted array of 0 and 1 Sort a binary array u
10 min read
Article Tags :
Practice Tags :