Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

Example:

Input: st[] = [1, 2, 3, 4]
Output: [1, 2, 3, 4]
Explanation:

[画像:3]

Input: st[] = [3, 2, 1]
Output: [3, 2, 1]
Explanation:

[画像:4]

Table of Content

[Approach 1] Recursive Approach

The idea is to use the recursion to reverse the given stack.

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 stack
voidinsertAtBottom(stack<int>&st,intx){

if(st.empty()){
st.push(x);
return;
}
// hold the top element and remove it
inttop=st.top();
st.pop();
// recursively call to reach the bottom
insertAtBottom(st,x);
st.push(top);
}
// function to reverse the stack
voidreverseStack(stack<int>&st){

if(st.empty())return;
// hold the top element and remove it
inttop=st.top();
st.pop();
// reverse the remaining stack
reverseStack(st);
// insert the held element at the bottom
insertAtBottom(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 100
structmyStack{
intarr[MAX];
inttop;
};
// function to insert element at the bottom of the stack
voidinsertAtBottom(structmyStack*st,intx){
if(st->top==-1){
st->arr[++st->top]=x;
return;
}
// hold the top element and remove it
inttemp=st->arr[st->top--];
// recursively call to reach the bottom
insertAtBottom(st,x);
st->arr[++st->top]=temp;
}
// function to reverse the stack
voidreverseStack(structmyStack*st){
if(st->top==-1)return;
// hold the top element and remove it
inttemp=st->arr[st->top--];
// reverse the remaining stack
reverseStack(st);
// insert the held element at the bottom
insertAtBottom(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;
class GfG{
// function to insert element at the bottom of the stack
staticvoidinsertAtBottom(Stack<Integer>st,intx){
if(st.isEmpty()){
st.push(x);
return;
}
// hold the top element and remove it
inttop=st.pop();
// recursively call to reach the bottom
insertAtBottom(st,x);
st.push(top);
}
// function to reverse the stack
staticvoidreverseStack(Stack<Integer>st){
if(st.isEmpty())return;
// hold the top element and remove it
inttop=st.pop();
// reverse the remaining stack
reverseStack(st);
// insert the held element at the bottom
insertAtBottom(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 stack
def insertAtBottom(st, x):
 if not st:
 st.append(x)
 return
 # hold the top element and remove it
 top = st.pop()
 # recursively call to reach the bottom
 insertAtBottom(st, x)
 st.append(top)
# function to reverse the stack
def reverseStack(st):
 if not st:
 return
 # hold the top element and remove it
 top = st.pop()
 # reverse the remaining stack
 reverseStack(st)
 # insert the held element at the bottom
 insertAtBottom(st, top)
if __name__ == "__main__":
 st = [1, 2, 3, 4]
 reverseStack(st)
 
 while st:
 print(st.pop(), end=" ")
C#
usingSystem;
usingSystem.Collections.Generic;
classGfG{

// function to insert element at the bottom of the stack
staticvoidinsertAtBottom(Stack<int>st,intx){
if(st.Count==0){
st.Push(x);
return;
}
// hold the top element and remove it
inttop=st.Pop();
// recursively call to reach the bottom
insertAtBottom(st,x);
st.Push(top);
}
// function to reverse the stack
staticvoidreverseStack(Stack<int>st){
if(st.Count==0)return;
// hold the top element and remove it
inttop=st.Pop();
// reverse the remaining stack
reverseStack(st);
// insert the held element at the bottom
insertAtBottom(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 stack
functioninsertAtBottom(st,x){
if(st.length===0){
st.push(x);
return;
}
// hold the top element and remove it
lettop=st.pop();
// recursively call to reach the bottom
insertAtBottom(st,x);
st.push(top);
}
// function to reverse the stack
functionreverseStack(st){
if(st.length===0)return;
// hold the top element and remove it
lettop=st.pop();
// reverse the remaining stack
reverseStack(st);
// insert the held element at the bottom
insertAtBottom(st,top);
}
// driver code
letst=[];
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 stack
while(!st.empty()){
aux.push(st.top());
st.pop();
}

// swapping aux stack with st
swap(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 structure
structmyStack{
intarr[MAX];
inttop;
};
// initialize stack
voidinit(structmyStack*st){
st->top=-1;
}
// check empty
intisEmpty(structmyStack*st){
returnst->top==-1;
}
// push element
voidpush(structmyStack*st,intx){
if(st->top==MAX-1)return;
st->arr[++st->top]=x;
}
// pop element
intpop(structmyStack*st){
if(isEmpty(st))return-1;
returnst->arr[st->top--];
}
// get top
intpeek(structmyStack*st){
returnst->arr[st->top];
}
// function to reverse the stack
voidreverseStack(structmyStack*st){
structmyStackaux;
init(&aux);
// move all elements to auxiliary stack
while(!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;
class GfG{
publicstaticvoidreverseStack(Stack<Integer>st){
Stack<Integer>aux=newStack<>();
// move all elements to auxiliary stack
while(!st.isEmpty()){
aux.push(st.pop());
}
// replace original stack with auxiliary
st.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
def reverseStack(st):
 aux = []
 # move all elements to auxiliary stack
 while st:
 aux.append(st.pop())
 # replace original stack with auxiliary
 st[:] = aux
if __name__ == "__main__":
 st = []
 st.append(1)
 st.append(2)
 st.append(3)
 st.append(4)
 
 reverseStack(st)
 
 while st:
 print(st.pop(), end=" ")
C#
usingSystem;
usingSystem.Collections.Generic;
classGfG{
staticvoidreverseStack(refStack<int>st){
Stack<int>aux=newStack<int>();
// move all elements to auxiliary stack
while(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 stack
while(st.length>0){
aux.push(st.pop());
}
// replace original stack with auxiliary
st.push(...aux);
}
// Driver Code
letst=[];
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 

[フレーム]
Reverse a stack using recursion
Improve
Article Tags :

Explore

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.

AltStyle によって変換されたページ (->オリジナル) /