牛客66题(5)用两个栈来实现一个队列

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }
 
    int pop() {
        int a;
        if(stack2.empty()){
            while(!stack1.empty())
            { stack2.push(stack1.top());
                stack1.pop();}
        }
            a=stack2.top();
            stack2.pop();
            
            return a;
        }
   
 
private:
    stack<int> stack1;
    stack<int> stack2;
};

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。该题主要思路运用两个栈,入队时直接压入栈一,出栈时先将所有的栈一的元素压到栈二中同时栈一出栈清空,将栈二的顶部元素返回并出栈一次。其实还有个要点就是要判断栈二是否为空,如果是不空,栈二的栈顶永远是队列的队首元素。因此不空的时候队列需要出栈直接弹出栈二的首元素即可。
--------------------- 
作者:libinxxx 
来源:CSDN 
原文:https://blog.csdn.net/libinxxx/article/details/82844863 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/libinxxx/article/details/84380789