简体   繁体   中英

how to reverse a stack using recursion in C++

I am trying to reverse stack without using extra space through recursion. But unable to find my error.

Here is my code. It is printing the same stack again.

#include<iostream>
#include<stack>
using namespace std;
void insert( stack<int>& k , int j){
    k.push(j);
}
void reverse(stack<int> &s){
    if(s.empty()){
        return;
    }
    int temp = s.top();
    s.pop();
    reverse(s);
    insert(s,temp);
}
int main()
{   
    stack<int>s;
    for( int i = 5;i>0;i--){
        s.push(i);
    }
    reverse(s);
    while(!s.empty()){
       cout << s.top() << " ";
       s.pop();
    }   
    return 0;
}

Your recursivity is not correct. You remove the top, call the same function (reverse) recursively and then push it back on top. This does not change its position! The same applies to all elements recursively: they do not change their position. A pure recursive solution (without using another stack or any data structure like an array or a list) to your problem is impossible.

Your insert() function is incorrect since you only push temp into the stack and once the stack is empty the value of temp will be 5 so 5 is pushed then 4 and so on. Hence the stack is filled in the same order. This insert() should work.

void insert( stack<int>& k , int j){
    if(k.empty()){
        k.push(j);
        return;
    }
    int temp = k.top();
    k.pop();
    insert(k, j);
    k.push(temp);
}

insert() just inserts j to the bottom of the stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM