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

用两个栈实现队列

时间:2022-12-10 17:01:15浏览次数:34  
标签:两个 MyQueue 队列 top pop 实现 int push empty

请用栈实现一个队列,支持如下四种操作:

  • push(x) – 将元素x插到队尾;
  • pop() – 将队首的元素弹出,并返回该元素;
  • peek() – 返回队首元素;
  • empty() – 返回队列是否为空;
    class MyQueue {
    public:
        /** Initialize your data structure here. */
        stack<int> a, b;
        
        MyQueue() {
            
        }
        
        /** Push element x to the back of queue. */
        void push(int x) {
            a.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        int pop() {
            while (a.size() > 1) {
                b.push(a.top());
                a.pop();
            }
            int t = a.top(); a.pop();
            while (b.size()) {
                a.push(b.top());
                b.pop();
            }
            return t;
        }
        
        /** Get the front element. */
        int peek() {
            while (a.size() > 1) {
                b.push(a.top());
                a.pop();
            }
            int t = a.top();
            while (b.size()) {
                a.push(b.top());
                b.pop();
            }
            return t;
        }
        
        /** Returns whether the queue is empty. */
        bool empty() {
            return a.empty();
        }
    };
    
    /**
     * Your MyQueue object will be instantiated and called as such:
     * MyQueue obj = MyQueue();
     * obj.push(x);
     * int param_2 = obj.pop();
     * int param_3 = obj.peek();
     * bool param_4 = obj.empty();
     */
    

      

标签:两个,MyQueue,队列,top,pop,实现,int,push,empty
From: https://www.cnblogs.com/leetothemoon/p/16971869.html

相关文章