剑指offer 5:用两个栈实现队列

#include <iostream>
#include <stack>

using namespace std;

class Solution
{
public:
    void push(int node) {
        stackIn.push(node);//入栈
    }
    int pop() {
        int node = -1;
        if (this->empty() == true) { //判断两个栈是否为空
            cout << "null" << endl;
            return -1;
        }
        else {
            if (stackOut.empty() == true) { //输出栈为空,输入栈必不为空
                while(stackIn.empty() != true) {
                    node = stackIn.top();//把输入栈的元素压入输出栈
                    stackIn.pop();
                    stackOut.push(node);
                    cout << node << "导入输出栈" << endl;
                }
            }
            //输出栈不为空,直接弹出
            else {
                node = stackOut.top();
                stackOut.pop();
                cout << "队头元素" << endl;
            }
        }
        return node;
    }
    bool empty() {
        return (stackIn.empty() == true && stackOut.empty() == true);
    }
private:
    stack<int> stackIn;
    stack<int> stackOut;
};


int main()
{
    Solution solu;
    solu.push(1);
    solu.push(2);
    solu.push(3);
    solu.push(4);
    int node;
    while (solu.empty() != true) {
        cout << solu.pop();
    }

    return 0;
}






























猜你喜欢

转载自blog.csdn.net/liufanlibashanxi/article/details/85262607