Given a stack st[], Reverse the stack so that the top element becomes the bottom and the bottom element becomes the top, while preserving the order of the remaining elements accordingly.
The idea is to use the recursion to reverse the given stack.
First, we keep removing elements from the stackuntil stack becomes empty.
Once the stack is empty, we start going back in the recursion. At each step, instead of placing the element back on top, we insert it at the bottom of the stack.
To insert an element at the bottom, we recursively pop all elements, push the current element, and then put the popped elements back.
This way we will ensuring that the element that was originally at the top moves to the bottom, and gradually the entire stack gets reversed.
C++
#include<iostream>#include<stack>usingnamespacestd;// function to insert element at the bottom of the stackvoidinsertAtBottom(stack<int>&st,intx){if(st.empty()){st.push(x);return;}// hold the top element and remove itinttop=st.top();st.pop();// recursively call to reach the bottominsertAtBottom(st,x);st.push(top);}// function to reverse the stackvoidreverseStack(stack<int>&st){if(st.empty())return;// hold the top element and remove itinttop=st.top();st.pop();// reverse the remaining stackreverseStack(st);// insert the held element at the bottominsertAtBottom(st,top);}intmain(){stack<int>st;st.push(1);st.push(2);st.push(3);st.push(4);reverseStack(st);while(!st.empty()){cout<<st.top()<<" ";st.pop();}return0;}
C
#include<stdio.h>#include<stdlib.h>#define MAX 100structmyStack{intarr[MAX];inttop;};// function to insert element at the bottom of the stackvoidinsertAtBottom(structmyStack*st,intx){if(st->top==-1){st->arr[++st->top]=x;return;}// hold the top element and remove itinttemp=st->arr[st->top--];// recursively call to reach the bottominsertAtBottom(st,x);st->arr[++st->top]=temp;}// function to reverse the stackvoidreverseStack(structmyStack*st){if(st->top==-1)return;// hold the top element and remove itinttemp=st->arr[st->top--];// reverse the remaining stackreverseStack(st);// insert the held element at the bottominsertAtBottom(st,temp);}intmain(){structmyStackst;st.top=-1;st.arr[++st.top]=1;st.arr[++st.top]=2;st.arr[++st.top]=3;st.arr[++st.top]=4;reverseStack(&st);while(st.top!=-1){printf("%d ",st.arr[st.top--]);}return0;}
Java
importjava.util.Stack;classGfG{// function to insert element at the bottom of the stackstaticvoidinsertAtBottom(Stack<Integer>st,intx){if(st.isEmpty()){st.push(x);return;}// hold the top element and remove itinttop=st.pop();// recursively call to reach the bottominsertAtBottom(st,x);st.push(top);}// function to reverse the stackstaticvoidreverseStack(Stack<Integer>st){if(st.isEmpty())return;// hold the top element and remove itinttop=st.pop();// reverse the remaining stackreverseStack(st);// insert the held element at the bottominsertAtBottom(st,top);}publicstaticvoidmain(String[]args){Stack<Integer>st=newStack<>();st.push(1);st.push(2);st.push(3);st.push(4);reverseStack(st);while(!st.isEmpty()){System.out.print(st.pop()+" ");}}}
Python
# function to insert element at the bottom of the stackdefinsertAtBottom(st,x):ifnotst:st.append(x)return# hold the top element and remove ittop=st.pop()# recursively call to reach the bottominsertAtBottom(st,x)st.append(top)# function to reverse the stackdefreverseStack(st):ifnotst:return# hold the top element and remove ittop=st.pop()# reverse the remaining stackreverseStack(st)# insert the held element at the bottominsertAtBottom(st,top)if__name__=="__main__":st=[1,2,3,4]reverseStack(st)whilest:print(st.pop(),end=" ")
C#
usingSystem;usingSystem.Collections.Generic;classGfG{// function to insert element at the bottom of the stackstaticvoidinsertAtBottom(Stack<int>st,intx){if(st.Count==0){st.Push(x);return;}// hold the top element and remove itinttop=st.Pop();// recursively call to reach the bottominsertAtBottom(st,x);st.Push(top);}// function to reverse the stackstaticvoidreverseStack(Stack<int>st){if(st.Count==0)return;// hold the top element and remove itinttop=st.Pop();// reverse the remaining stackreverseStack(st);// insert the held element at the bottominsertAtBottom(st,top);}staticvoidMain(){Stack<int>st=newStack<int>();st.Push(1);st.Push(2);st.Push(3);st.Push(4);reverseStack(st);while(st.Count>0){Console.Write(st.Pop()+" ");}}}
JavaScript
// function to insert element at the bottom of the stackfunctioninsertAtBottom(st,x){if(st.length===0){st.push(x);return;}// hold the top element and remove itlettop=st.pop();// recursively call to reach the bottominsertAtBottom(st,x);st.push(top);}// function to reverse the stackfunctionreverseStack(st){if(st.length===0)return;// hold the top element and remove itlettop=st.pop();// reverse the remaining stackreverseStack(st);// insert the held element at the bottominsertAtBottom(st,top);}// driver codeletst=[];st.push(1);st.push(2);st.push(3);st.push(4);reverseStack(st);letres=[];while(st.length>0){res.push(st.pop());}console.log(res.join(" "));
Output
1 2 3 4
Time Complexity: O(n2) Auxiliary Space: O(n), due to recursion stack
[Approach 2] Iterative Approach - O(n) Time and O(n) Space
We use an auxiliary stack to hold elements while popping them from the original stack. Since stacks are LIFO, pushing all elements into the auxiliary stack will naturally reverse their order. Finally, we replace the original stack with the auxiliary stack.
C++
#include<iostream>#include<stack>usingnamespacestd;voidreverseStack(stack<int>&st){stack<int>aux;// move all elements to auxiliary stackwhile(!st.empty()){aux.push(st.top());st.pop();}// swapping aux stack with stswap(st,aux);}intmain(){stack<int>st;st.push(1);st.push(2);st.push(3);st.push(4);reverseStack(st);while(!st.empty()){cout<<st.top()<<" ";st.pop();}return0;}
C
#include<stdio.h>#include<stdlib.h>#define MAX 100// stack structurestructmyStack{intarr[MAX];inttop;};// initialize stackvoidinit(structmyStack*st){st->top=-1;}// check emptyintisEmpty(structmyStack*st){returnst->top==-1;}// push elementvoidpush(structmyStack*st,intx){if(st->top==MAX-1)return;st->arr[++st->top]=x;}// pop elementintpop(structmyStack*st){if(isEmpty(st))return-1;returnst->arr[st->top--];}// get topintpeek(structmyStack*st){returnst->arr[st->top];}// function to reverse the stackvoidreverseStack(structmyStack*st){structmyStackaux;init(&aux);// move all elements to auxiliary stackwhile(!isEmpty(st)){push(&aux,pop(st));}// replace original stack with auxiliary*st=aux;}intmain(){structmyStackst;init(&st);push(&st,1);push(&st,2);push(&st,3);push(&st,4);reverseStack(&st);while(!isEmpty(&st)){printf("%d ",pop(&st));}return0;}
Java
importjava.util.Stack;classGfG{publicstaticvoidreverseStack(Stack<Integer>st){Stack<Integer>aux=newStack<>();// move all elements to auxiliary stackwhile(!st.isEmpty()){aux.push(st.pop());}// replace original stack with auxiliaryst.addAll(aux);}publicstaticvoidmain(String[]args){Stack<Integer>st=newStack<>();st.push(1);st.push(2);st.push(3);st.push(4);reverseStack(st);while(!st.isEmpty()){System.out.print(st.pop()+" ");}}}
Python
defreverseStack(st):aux=[]# move all elements to auxiliary stackwhilest:aux.append(st.pop())# replace original stack with auxiliaryst[:]=auxif__name__=="__main__":st=[]st.append(1)st.append(2)st.append(3)st.append(4)reverseStack(st)whilest:print(st.pop(),end=" ")
C#
usingSystem;usingSystem.Collections.Generic;classGfG{staticvoidreverseStack(refStack<int>st){Stack<int>aux=newStack<int>();// move all elements to auxiliary stackwhile(st.Count>0){aux.Push(st.Peek());st.Pop();}st=aux;}staticvoidMain(){Stack<int>st=newStack<int>();st.Push(1);st.Push(2);st.Push(3);st.Push(4);reverseStack(refst);while(st.Count>0){Console.Write(st.Peek()+" ");st.Pop();}}}
JavaScript
functionreverseStack(st){letaux=[];// move all elements to auxiliary stackwhile(st.length>0){aux.push(st.pop());}// replace original stack with auxiliaryst.push(...aux);}// Driver Codeletst=[];st.push(1);st.push(2);st.push(3);st.push(4);reverseStack(st);letres=[];while(st.length>0){res.push(st.pop());}console.log(res.join(" "));