仅用递归函数和栈操作逆序一个栈

不能使用任何其它数据结构,包括数组,不能新开栈空间

#include <iostream>
#include <stack>
using namespace std;

int getAndRemoveLast(stack<int> &orignal)
{
    int result = orignal.top();
    orignal.pop();
    if(orignal.empty())
        return result;
    else
    {
        int last = getAndRemoveLast(orignal);
        orignal.push(result);
        return last;
    }
}

void rever(stack<int> &orignal)
{
    if(orignal.empty())
        return;
    int val = getAndRemoveLast(orignal);
    rever(orignal);
    orignal.push(val);
}

猜你喜欢

转载自blog.csdn.net/wzc2608/article/details/80564164
今日推荐