Implement Queue using Stacks LeetCode solution in Java

1
class MyQueue {
2

3
private final Deque<Integer> stack = new ArrayDeque<>();
4
private final Deque<Integer> temp = new ArrayDeque<>();
5

6
/** Initialize your data structure here. */
7
public MyQueue() {}
8

9
/** Pushes element x to the back of the queue. */
10
public void push(int x) {
11
stack.push(x);
12
}
13

14
/**
15
* @return the element at the front of the queue and remove it.
16
*/
17
public int pop() {
18
while (stack.size() > 1) temp.push(stack.pop());
19

20
var val = stack.pop();
21
while (!temp.isEmpty()) stack.push(temp.pop());
22

23
return val;
24
}
25

26
/**
27
* @return the element at the front of the queue.
28
*/
29
public int peek() {
30
while (stack.size() > 1) temp.push(stack.pop());
31

32
var val = stack.peek();
33
while (!temp.isEmpty()) stack.push(temp.pop());
34

35
return val;
36
}
37

38
/**
39
* @return true if the queue is empty, false otherwise.
40
*/
41
public boolean empty() {
42
return stack.isEmpty();
43
}
44
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0