-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathImplement Queue using Stacks.java
53 lines (43 loc) · 1.12 KB
/
Implement Queue using Stacks.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Runtime: 1 ms (Top 70.23%) | Memory: 41.5 MB (Top 77.34%)
class MyQueue {
private final Deque<Integer> stack = new ArrayDeque<>();
private final Deque<Integer> temp = new ArrayDeque<>();
/**
* Initialize your data structure here.
*/
public MyQueue() {}
/**
* Pushes element x to the back of the queue.
*/
public void push(int x) {
stack.push(x);
}
/**
* @return the element at the front of the queue and remove it.
*/
public int pop() {
while (stack.size() > 1)
temp.push(stack.pop());
var val = stack.pop();
while (!temp.isEmpty())
stack.push(temp.pop());
return val;
}
/**
* @return the element at the front of the queue.
*/
public int peek() {
while (stack.size() > 1)
temp.push(stack.pop());
var val = stack.peek();
while (!temp.isEmpty())
stack.push(temp.pop());
return val;
}
/**
* @return true if the queue is empty, false otherwise.
*/
public boolean empty() {
return stack.isEmpty();
}
}