其他分享
首页 > 其他分享> > 用两个栈来实现一个队列

用两个栈来实现一个队列

作者:互联网

用两个栈来实现一个队列,完成队列的Push和Pop操作。

队列中的元素为int类型。

 

实现思路:

    利用栈last in first out 的特性,使用两个栈可以实现队列的pop和push操作。

    push: 往stack1中push元素。

    pop: 先判断stack2是否为空,若为空,将stack1中的所有元素pop至stack2中,取出stack2的栈顶元素pop出去

       若不为空,直接取出stack2的栈顶元素pop出去;

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

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

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

 

标签:队列,pop,实现,int,push,栈来,stack2,stack1
来源: https://www.cnblogs.com/-xinxin/p/10725705.html