class MyQueue {
Stack<Integer> pos = new Stack<Integer>();
Stack<Integer> neg = new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
if (!pos.isEmpty()) while (!pos.isEmpty()) neg.push(pos.pop());
neg.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if (pos.isEmpty()) while (!neg.isEmpty()) pos.push(neg.pop());
pos.pop();
}
// Get the front element.
public int peek() {
if (pos.isEmpty()) while (!neg.isEmpty()) pos.push(neg.pop());
return pos.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return pos.isEmpty() && neg.isEmpty();
}
}
LeetCode 232. Implement Queue using Stacks
最新推荐文章于 2024-08-03 23:57:26 发布