-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathImplementQueueUsingStacks.java
78 lines (68 loc) · 1.9 KB
/
ImplementQueueUsingStacks.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package io.ziheng.stack.leetcode;
import java.util.Deque;
import java.util.LinkedList;
/**
* LeetCode 232. Implement Queue using Stacks
* https://leetcode.com/problems/implement-queue-using-stacks/
*/
public class ImplementQueueUsingStacks {
public static void main(String[] args) {
ImplementQueueUsingStacks queue = new ImplementQueueUsingStacks();
int capacity = 10;
for (int i = 0; i < capacity; i++) {
queue.push(i);
}
while (!queue.empty()) {
System.out.printf("%d, ", queue.pop());
}
System.out.println();
}
private Deque<Integer> primaryStack;
private Deque<Integer> secondaryStack;
/**
* Initialize your data structure here.
*/
public ImplementQueueUsingStacks() {
this.primaryStack = new LinkedList<>();
this.secondaryStack = new LinkedList<>();
}
/**
* Push element x to the back of queue.
*/
public void push(int x) {
primaryStack.push(x);
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
while (!primaryStack.isEmpty()) {
secondaryStack.push(primaryStack.pop());
}
int ret = secondaryStack.pop();
while (!secondaryStack.isEmpty()) {
primaryStack.push(secondaryStack.pop());
}
return ret;
}
/**
* Get the front element.
*/
public int peek() {
while (!primaryStack.isEmpty()) {
secondaryStack.push(primaryStack.pop());
}
int ret = secondaryStack.peek();
while (!secondaryStack.isEmpty()) {
primaryStack.push(secondaryStack.pop());
}
return ret;
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return primaryStack.isEmpty() && secondaryStack.isEmpty();
}
}
/* EOF */