AcWing 20. 用两个栈实现队列
原题链接
简单
作者:
小轩喵灬
,
2025-01-13 23:34:05
,
所有人可见
,
阅读 1
class MyQueue {
private Deque<Integer> deque1;
private Deque<Integer> deque2;
/** Initialize your data structure here. */
public MyQueue() {
deque1 = new ArrayDeque<>();
deque2 = new ArrayDeque<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
deque1.push(x);
}
void copy(Deque<Integer> deque1, Deque<Integer> deque2) {
while(!deque1.isEmpty()) {
deque2.push(deque1.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
copy(deque1, deque2);
int res = deque2.pop();
copy(deque2, deque1);
return res;
}
/** Get the front element. */
public int peek() {
copy(deque1, deque2);
int res = deque2.peek();
copy(deque2, deque1);
return res;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return deque1.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();
*/