Implement Queue using Stacks

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.

pop() -- Removes the element from in front of queue.

peek() -- Get the front element.

empty() -- Return whether the queue is empty.

Notes:

You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.

Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.

You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

本题中需要使用栈来模拟队列的使用,显而易见的是 栈和队列最大的不同是 栈只能在栈顶操作 即只能在一头做操作  而队列需要在两头做操作  哪怕现在要用栈来模拟队列 那么也改变不了栈原有的属性  比如当要读取队列队首元素时 栈显然不能一部到位  需要出一次栈   这很显然想到需要多个栈  至少两个  在需要操作队列队首的时候  从一个栈弹出元素压入另一个栈  那么顺序也刚好反了一下  使得现的栈顶即为队首  然而队尾加入元素还是和栈的操作没有区别 

这说明每次做队尾和队首操作时  需要在两个栈中不停的变化  所以两个栈就够了  关于判断是否为空  也即只要判断栈是否为空即可

代码:

class MyQueue {

private:
    stack<int>stack_in;
    stack<int>stack_out;
public:
    /** Initialize your data structure here. */
    MyQueue() {
 
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        stack_in.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        while(!stack_in.empty())
        {
            stack_out.push(stack_in.top());
            stack_in.pop();
        }
        int res=stack_out.top();
        stack_out.pop();
        while(!stack_out.empty())
        {
            stack_in.push(stack_out.top());
            stack_out.pop();
        }
        return res;
    }
    
    /** Get the front element. */
    int peek() {
        while(!stack_in.empty())
        {
            stack_out.push(stack_in.top());
            stack_in.pop();
        }
        int res=stack_out.top();
        while(!stack_out.empty())
        {
            stack_in.push(stack_out.top());
            stack_out.pop();
        }
        return res;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return stack_in.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/weiyi-mgh/p/6413658.html