19_232. 用栈实现队列


题目描述:

解题思路:

  • 想着利用两个栈stack1和stack2,把stack1当作队列,其pop和队列的pop一样,然后每次push数据,就把stack1中的数据,依次出栈并入栈stack2,这样stack2中的顺序,就是最开始的入栈顺序,然后将新数据入栈stack2,再把stack2中所有数据依次出栈并入栈stack1。结果超出时间限制。
  • 题解中并不需要每次都倒腾两遍,而是利用两个栈,一个栈inStack当做入队时存放数据,一个outStack当做出队存放数据的栈,因此每次入队,只需要inStack.push()即可,出队时,如果outStack为空,则将inStack数据全部出栈,放入outStack,再出栈即可。这种方法就避免了每次都要出栈入栈两次,减少了所消耗的时间。
代码
class MyQueue {
    Deque inStack= null;
    Deque outStack = null;
    public MyQueue() {
        inStack = new LinkedList();
        outStack = new LinkedList();
    }
    
    public void push(int x) {
        inStack.push(x);
    }
    
    public int pop() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        } 
        return outStack.pop();
    }
    
    public int peek() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        } 
        return outStack.peek();
    }
    
    public boolean empty() {
        return (inStack.isEmpty() && outStack.isEmpty());
    }
}

/**
 * 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();
 * boolean param_4 = obj.empty();
 */