-
Notifications
You must be signed in to change notification settings - Fork 6
/
ImplementStackUsingQueues.java
79 lines (69 loc) · 1.94 KB
/
ImplementStackUsingQueues.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
79
package io.ziheng.queue.leetcode;
import java.util.Queue;
import java.util.LinkedList;
/**
* LeetCode 225. Implement Stack using Queues
* https://leetcode.com/problems/implement-stack-using-queues/
*/
public class ImplementStackUsingQueues {
public static void main(String[] args) {
ImplementStackUsingQueues stack = new ImplementStackUsingQueues();
int capacity = 10;
for (int i = 0; i < capacity; i++) {
stack.push(i);
}
while (!stack.empty()) {
System.out.printf("%d, ", stack.pop());
}
System.out.println();
}
private Queue<Integer> primaryQueue;
private Queue<Integer> secondaryQueue;
/**
* Initialize your data structure here.
*/
public ImplementStackUsingQueues() {
this.primaryQueue = new LinkedList<>();
this.secondaryQueue = new LinkedList<>();
}
/**
* Push element x onto stack.
*/
public void push(int x) {
primaryQueue.offer(x);
}
/**
* Removes the element on top of the stack and returns that element.
*/
public int pop() {
while (primaryQueue.size() > 1) {
secondaryQueue.offer(primaryQueue.poll());
}
int ret = primaryQueue.poll();
while (!secondaryQueue.isEmpty()) {
primaryQueue.offer(secondaryQueue.poll());
}
return ret;
}
/**
* Get the top element.
*/
public int top() {
while (primaryQueue.size() > 1) {
secondaryQueue.offer(primaryQueue.poll());
}
int ret = primaryQueue.peek();
secondaryQueue.offer(primaryQueue.poll());
while (!secondaryQueue.isEmpty()) {
primaryQueue.offer(secondaryQueue.poll());
}
return ret;
}
/**
* Returns whether the stack is empty.
*/
public boolean empty() {
return primaryQueue.isEmpty() && secondaryQueue.isEmpty();
}
}
/* EOF */