【剑指offer】9、用两个栈实现队列

题目

用两个栈实现队列。队列声明如下,实现appendTail和deleteHead,分别完成在队列尾部插入节点,和头部删除节点的功能。

思路

尾部插入:直接向stack1压入即可

头部删除:先进先出,因此在删除时,若stack1非空,先将stack1全部元素压入stack2,然后stack2.pop()即可

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

    int pop() {
        if (stack2.size() == 0)
        {
            while ( stack1.size() > 0){
                int temp = stack1.top();
                stack1.pop();
                stack2.push(temp);
            }
        }
        int head = stack2.top();
        stack2.pop();
        
        return head;
    }

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

猜你喜欢

转载自www.cnblogs.com/shiganquan/p/9281859.html