LeetCode 232. 用栈实现队列 [Implement Queue using Stacks (Easy)]

时间:2020-05-14
本文章向大家介绍LeetCode 232. 用栈实现队列 [Implement Queue using Stacks (Easy)],主要包括LeetCode 232. 用栈实现队列 [Implement Queue using Stacks (Easy)]使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

来源:力扣(LeetCode)


class MyQueue {
public:
    stack<int> stack1;
    stack<int> stack2;
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        stack1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if (stack2.empty())
        {
            while (!stack1.empty())  //1栈全部灌入2栈
            {
                stack2.push(stack1.top());
                stack1.pop();
            }
                
        }
        int res = stack2.top(); stack2.pop();
        return res;
    }
    
    /** Get the front element. */
    int peek() {
        if (stack2.empty())  //2栈为空
        {
            while (!stack1.empty())
            {
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        int res = stack2.top();
        return res;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return stack1.empty() && stack2.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

原文地址:https://www.cnblogs.com/ZSY-blog/p/12887074.html