Skip to content

Commit 5a23685

Browse files
authored
Create Design Front Middle Back Queue.java
1 parent 9064ac3 commit 5a23685

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
class FrontMiddleBackQueue {
2+
3+
Deque<Integer> frontQueue;
4+
Deque<Integer> backQueue;
5+
6+
public FrontMiddleBackQueue() {
7+
frontQueue = new ArrayDeque<>();
8+
backQueue = new ArrayDeque<>();
9+
}
10+
11+
public void pushFront(int val) {
12+
frontQueue.addFirst(val);
13+
}
14+
15+
public void pushMiddle(int val) {
16+
while (frontQueue.size() + 1 < backQueue.size()) {
17+
frontQueue.addLast(backQueue.removeFirst());
18+
}
19+
while (frontQueue.size() > backQueue.size()) {
20+
backQueue.addFirst(frontQueue.removeLast());
21+
}
22+
frontQueue.addLast(val);
23+
}
24+
25+
public void pushBack(int val) {
26+
backQueue.addLast(val);
27+
}
28+
29+
public int popFront() {
30+
return frontQueue.isEmpty()
31+
? (backQueue.isEmpty() ? -1 : backQueue.removeFirst())
32+
: frontQueue.removeFirst();
33+
}
34+
35+
public int popMiddle() {
36+
if (frontQueue.isEmpty() && backQueue.isEmpty()) {
37+
return -1;
38+
}
39+
while (frontQueue.size() < backQueue.size()) {
40+
frontQueue.addLast(backQueue.removeFirst());
41+
}
42+
while (frontQueue.size() > backQueue.size() + 1) {
43+
backQueue.addFirst(frontQueue.removeLast());
44+
}
45+
return !frontQueue.isEmpty() ? frontQueue.removeLast() : backQueue.removeFirst();
46+
}
47+
48+
public int popBack() {
49+
return backQueue.isEmpty()
50+
? (frontQueue.isEmpty() ? -1 : frontQueue.removeLast())
51+
: backQueue.removeLast();
52+
}
53+
}
54+
55+
/**
56+
* Your FrontMiddleBackQueue object will be instantiated and called as such:
57+
* FrontMiddleBackQueue obj = new FrontMiddleBackQueue();
58+
* obj.pushFront(val);
59+
* obj.pushMiddle(val);
60+
* obj.pushBack(val);
61+
* int param_4 = obj.popFront();
62+
* int param_5 = obj.popMiddle();
63+
* int param_6 = obj.popBack();
64+
*/

0 commit comments

Comments
 (0)