Leetcode232.用堆栈实现队列

使用栈实现队列的下列操作:

push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。

链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
思路:入栈的时候 还是正常入栈,出栈的时候将所有的输入栈里面的东西输出 压到输出栈里面,然后再输出

class MyQueue {
    Stack<Integer> S1;
    Stack<Integer> S2;

    /** Initialize your data structure here. */
    public MyQueue() {
        S1=new Stack<>();
        S2=new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        S1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while(S2.isEmpty())//如果输出栈为空
        {
            while(!S1.isEmpty())
            {
                S2.push(S1.pop());      //把输入栈的全部放入输出栈
            }
            
        }
        return S2.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        while(S2.isEmpty())//如果输出栈为空
        {
            while(!S1.isEmpty())
            {
                S2.push(S1.pop());      //把输入栈的全部放入输出栈
            }
            
        }
        return S2.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return S1.isEmpty() && S2.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();
 */
原文地址:https://www.cnblogs.com/William-xh/p/13778402.html