stack1
will accept input elements forpush()
stack2
will output elements forpop()
,peek()
- when trying to do a
pop()
orpeek()
on our queue, ifstack2
is empty, we will move all elements fromstack1
tostack2
. This will reverse the order of the elements, giving us the correct order when we callpop()
orpeek()
on our queue.
class MyQueue {
private Stack<Integer> stack1 = new Stack();
private Stack<Integer> stack2 = new Stack();
public void push(int x) {
stack1.push(x);
}
public int pop() {
if (stack2.isEmpty()) {
shiftStacks();
}
return stack2.pop();
}
public int peek() {
if (stack2.isEmpty()) {
shiftStacks();
}
return stack2.peek();
}
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
private void shiftStacks() {
while (!stack1.isEmpty()) {
int temp = stack1.pop();
stack2.push(temp);
}
}
}
- LeetCode problem statement says it will not perform invalid operations such as
peek()
orpop()
on an empty stack. A more general solution should check for an empty queue inpeek()
andpop()
, and if the queue is empty, either:- throw an error
- return null (which would require changing the return value from
int
toInteger
)
add()
is a better name thanpush()
for a queue.remove()
is a better name thanpop()
for a queue.
- Time Complexity: O(1) amortized time for
push()
,pop()
,peek()
,empty()
, as each element is only moved fromstack1
tostack2
at most once. - Space Complexity: O(1) for each element being put into our queue.