'Reversing a Stack with the help of another empty stack in C++ using recursion?
My approach to this question is that as recursion works using stack ,So if my input is some n numbers,recursion will provide me reverse of the stack from 1 to n and for adding 0th element ,I'll first copy the stack(Say S1) into an empty stack(Say S2) and push 0th element into S1 and then copy back the element from Stack S2 to S1. This is my code and I'm not able to figure out the problem to implement my approach.
void reverseStack(stack<int> &input, stack<int> &extra) {
if(input.size()==0)
{
return;
}
int x=input.top();
input.pop();
reverseStack(input,extra);
for(int i=0;i<input.size();i++)
{
extra.push(input.top());
input.pop();
}
input.push(x);
for(int i=0;i<extra.size();i++)
{
input.push(extra.top());
extra.pop();
}
}
Solution 1:[1]
You should declare size variables for input and extra stack.
void reverseStack(stack<int> &input, stack<int> &extra) {
// Write your code here
if(input.size()==0)
{
return;
}
int x=input.top();
input.pop();
reverseStack(input,extra);
int size1 = input.size();
for(int i=0;i<size1;i++)
{
extra.push(input.top());
input.pop();
}
input.push(x);
int size2 = extra.size();
for(int i=0;i<size2;i++)
{
input.push(extra.top());
extra.pop();
}
}
Solution 2:[2]
void reverseStack(stack<int> &input, stack<int> &extra) {
if(input.empty())
{
return;
}
int x = input.top();
input.pop();
reverseStack(input,extra);
while(!input.empty())
{
extra.push(input.top());
input.pop();
}
input.push(x);
while(!extra.empty())
{
input.push(extra.top());
extra.pop();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Atishay Jain |
| Solution 2 | David Buck |
