leetcode 链接:化栈为队
《程序员面试代码指南》by 左程云 中相同题目:★★☆☆由两个栈组成的队列
题目
实现一个 MyQueue 类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();queue.push(1);queue.push(2);queue.peek(); // 返回 1queue.pop(); // 返回 1queue.empty(); // 返回 false
解答 & 代码
设置两个栈:
- 压入栈 
stackPush:push 数据时只 push 到这个栈 - 弹出栈 
stackPop:pop 数据时指从这个栈中弹出 
设置一个函数 stackPushTostackPop() :仅当栈 stackPop 为空栈时,将栈 stackPush 的所有元素弹出并压入到栈 stackPop 中
class MyQueue {
private:
    stack<int> stackPush;
    stack<int> stackPop;
    void stackPushTostackPop()
    {
        if(stackPop.empty())
        {
            while(!stackPush.empty())
            {
                int val = stackPush.top();
                stackPush.pop();
                stackPop.push(val);
            }
        }
    }
public:
    /** Initialize your data structure here. */
    MyQueue() {       
    }
    /** Push element x to the back of queue. */
    void push(int x) {
        stackPush.push(x);
        stackPushTostackPop();
    }
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        stackPushTostackPop();
        int val = stackPop.top();
        stackPop.pop();
        return val;
    }
    /** Get the front element. */
    int peek() {
        stackPushTostackPop();
        return stackPop.top();
    }
    /** Returns whether the queue is empty. */
    bool empty() {
        return stackPush.empty() && stackPop.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();
 */
执行结果:
执行结果:通过
执行用时:4 ms, 在所有 C++ 提交中击败了 32.0% 的用户
内存消耗:6.6 MB, 在所有 C++ 提交中击败了 83.7% 的用户
                    