#1670
Design Front Middle Back Queue
specialist · 770 · lc medium +31 · 57% accepted · 816 likes · top 52%
Description
Design a FrontMiddleBackQueue supporting push and pop at the front, middle, and back. When there are two possible middle positions, use the frontmost one. Implement:
- FrontMiddleBack() initializes the queue.
- void pushFront(int val) inserts val at the front.
- void pushMiddle(int val) inserts val in the middle.
- void pushBack(int val) inserts val at the back.
- int popFront() removes and returns the front element, or -1 if empty.
- int popMiddle() removes and returns the middle element, or -1 if empty.
- int popBack() removes and returns the back element, or -1 if empty.
Example 1:
Input:
["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"]
[[], [1], [2], [3], [4], [], [], [], [], []]
Output:
[null, null, null, null, null, 1, 3, 4, 2, -1]
Example 2:
Explanation:
FrontMiddleBackQueue q = new FrontMiddleBackQueue();
q.pushFront(1); // [1]
q.pushBack(2); // [1, 2]
q.pushMiddle(3); // [1, 3, 2]
q.pushMiddle(4); // [1, 4, 3, 2]
q.popFront(); // return 1 -> [4, 3, 2]
q.popMiddle(); // return 3 -> [4, 2]
q.popMiddle(); // return 4 -> [2]
q.popBack(); // return 2 -> []
q.popFront(); // return -1 -> [] (The queue is empty)
Code
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