请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
答案:
class MyQueue { private Stack<Integer> one; private Stack<Integer> two; public MyQueue() { one = new Stack<Integer>(); two = new Stack<Integer>(); } public void push(int x) { one.push(x); } public int pop() { // 注意是if而不是while if(two.isEmpty()) { while(!one.isEmpty()) { two.push(one.pop()); } } return two.pop(); } public int peek() { if(two.isEmpty()) { while(!one.isEmpty()) { two.push(one.pop()); } } //注意:出栈是top,栈顶是peek return two.peek(); } public boolean empty() { return one.isEmpty() && two.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(); */