-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathImplementQueueusingStacks.java
More file actions
37 lines (34 loc) · 978 Bytes
/
ImplementQueueusingStacks.java
File metadata and controls
37 lines (34 loc) · 978 Bytes
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
class MyQueue {
Stack<Integer> stack = new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
stack.push(x);
}
// Removes the element from in front of queue.
public void pop() {
Stack<Integer> container = new Stack<Integer>();
while (stack.size() > 1) {
container.push(stack.pop());
}
stack.pop();
while (!container.isEmpty()) {
stack.push(container.pop());
}
}
// Get the front element.
public int peek() {
Stack<Integer> container = new Stack<Integer>();
while (stack.size() > 1) {
container.push(stack.pop());
}
int firstValue = stack.peek();
while (!container.isEmpty()) {
stack.push(container.pop());
}
return firstValue;
}
// Return whether the queue is empty.
public boolean empty() {
return stack.size() == 0;
}
}