力扣 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(双端队列)来模仿一个栈,只有是规范的栈操作即可。 示例 1:输出:["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 1myQueue.pop(); // return 1, queue is [2]myQueue.empty(); // return false起源:力扣(LeetCode)链接:https://leetcode.cn/problems/implement-queue-using-stacks著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法:两个栈,一个用于存进入的数据,另一个存要进来的数据

class MyQueue {    Stack<Integer> stack1 = new Stack();    Stack<Integer> stack2 = new Stack();    public MyQueue() {    }    public void push(int x) {        stack1.push(x);    }    public int pop() {        if(stack2.isEmpty()){            in2out();        }        return stack2.pop();    }    public int peek() {        if(stack2.isEmpty()){            in2out();        }        return stack2.peek();    }    public boolean empty() {        return stack1.isEmpty() && stack2.isEmpty();    }    private void in2out() {        while (!stack1.isEmpty()) {            stack2.push(stack1.pop());        }    }}