递归函数和栈实现队列

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

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

void reverse(stack<int>& stack) {
    if (stack.empty()){
        return;
    }
    int value = getAndRemoveLastElement(stack);
    reverse(stack);
    stack.push(value);

}
int main() {
    stack<int> test;
    test.push(1);
    test.push(2);
    test.push(3);
    reverse(test);
    while (!test.empty())
    {
        cout << test.top() << endl;
        test.pop();
    }
    return 0;
}

 

posted @ 2019-07-27 10:47  木子石页  阅读(194)  评论(0编辑  收藏  举报