8.用两个栈实现队列

用两个栈实现队列

1.题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

2.思路

1.push操作插入stack1
2.pop操作:当stack2为空时,把stack1中所有元素插入stack2,pop操作对stack2进行。

3.代码

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        if(stack2.empty()){
            while(!stack1.empty()){
                int data = stack1.top();
                stack1.pop();
                stack2.push(data);
            }
        }
        if(stack1.empty() && stack2.empty()){
            logic_error ex("emtpy!");
            throw exception(ex);
        }
        int res = stack2.top();
        stack2.pop();
        return res;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
发布了71 篇原创文章 · 获赞 0 · 访问量 799

猜你喜欢

转载自blog.csdn.net/jiangdongxiaobawang/article/details/103917011