力扣232 用栈实现队列
题目:
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
    void push(int x) 将元素 x 推到队列的末尾
    int pop() 从队列的开头移除并返回元素
    int peek() 返回队列开头的元素
    boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
- 只能 使用标准的栈操作 —— 也就是只有push to top,peek/pop from top,size, 和is empty操作是合法的。
- 所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例:
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
思路:

用两个栈模拟队列操作
class MyQueue {
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;
    public MyQueue() {
        stackIn = new Stack<>(); // 负责进栈
        stackOut = new Stack<>(); // 负责出栈
    }
    
    public void push(int x) {// 将元素 x 推到队列的末尾
        stackIn.push(x);//入栈
    }
    
    public int pop() {//从队列的开头移除并返回元素
        if (stackOut.isEmpty()){//当出栈为空时,要把入栈的所有元素都入出栈
            while (!stackIn.isEmpty()){
                stackOut.push(stackIn.pop());
            }
        }
        int result = stackOut.pop();//弹出第一个元素
        return result;
    }
    
    public int peek() {//返回队列开头的元素
        int result=this.pop();
        stackOut.push(result);// 因为pop函数弹出了元素res,所以再添加回去
        return result;
    }
    
    public boolean empty() {//如果队列为空,返回 true ;否则,返回 false
        return stackIn.isEmpty() && stackOut.isEmpty();
    }
}
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号