-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyStack.java
83 lines (72 loc) · 2.01 KB
/
MyStack.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
80
81
82
83
package org.sean.stack;
import java.util.LinkedList;
import java.util.Queue;
/***
* 225. Implement Stack using Queues
*/
class MyStack {
private final Queue<Integer> queue;
private final Queue<Integer> queueBackup;
private boolean mainQueueUsed;
public MyStack() {
queue = new LinkedList<>();
queueBackup = new LinkedList<>();
mainQueueUsed = true;
}
public void push(int x) {
if (mainQueueUsed)
queue.offer(x);
else
queueBackup.offer(x);
}
public int pop() {
return checkTopElem(true);
}
private int checkTopElem(boolean needPop) {
if (mainQueueUsed) {
mainQueueUsed = !mainQueueUsed;
while (!queue.isEmpty()) {
int elem = queue.poll();
if (queue.isEmpty()) {
if (needPop)
return elem;
else {
queueBackup.offer(elem);
return elem;
}
} else {
queueBackup.offer(elem);
}
}
} else {
mainQueueUsed = !mainQueueUsed;
while (!queueBackup.isEmpty()) {
int elem = queueBackup.poll();
if (queueBackup.isEmpty()) {
if (needPop)
return elem;
else {
queue.offer(elem);
return elem;
}
} else
queue.offer(elem);
}
}
throw new IllegalStateException("");
}
public int top() {
return checkTopElem(false);
}
public boolean empty() {
return queue.isEmpty() && queueBackup.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/