【剑指Offer】用两个栈实现队列(栈、队列)

题目链接

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:入队两个数据结构没有什么区别,出队不一样,根据栈(LIFO)和队列(FIFO)的性质,可以知道出队是将栈1的底部元素出队,所以将所有元素压入另外一个栈(必须是空,若不为空,栈顶元素即为队列的出队元素),然后弹出栈顶元素。

代码:

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

    int pop() {
        int now;
        if(stack2.empty()) {
            while(!stack1.empty()) {
                now=stack1.top();
                stack1.pop();
                stack2.push(now);
            }
        }
        now=stack2.top();
        stack2.pop();
        return now;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

猜你喜欢

转载自blog.csdn.net/feng_zhiyu/article/details/80885027