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();
}
}
Aucun commentaire:
Enregistrer un commentaire