设计前中后队列

请你设计一个队列,支持在前,中,后三个位置的 pushpop 操作。

请你完成 FrontMiddleBack 类:

  • FrontMiddleBack() 初始化队列。
  • void pushFront(int val)val 添加到队列的 最前面
  • void pushMiddle(int val)val 添加到队列的 正中间
  • void pushBack(int val)val 添加到队里的 最后面
  • int popFront()最前面 的元素从队列中删除并返回值,如果删除之前队列为空,那么返回 -1
  • int popMiddle()正中间 的元素从队列中删除并返回值,如果删除之前队列为空,那么返回 -1
  • int popBack()最后面 的元素从队列中删除并返回值,如果删除之前队列为空,那么返回 -1

请注意当有 两个 中间位置的时候,选择靠前面的位置进行操作。比方说:

  • 6 添加到 [1, 2, 3, 4, 5] 的中间位置,结果数组为 [1, 2, **6**, 3, 4, 5]
  • [1, 2, **3**, 4, 5, 6] 的中间位置弹出元素,返回 3 ,数组变为 [1, 2, 4, 5, 6]

示例 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
输入:
["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"]
[[], [1], [2], [3], [4], [], [], [], [], []]
输出:
[null, null, null, null, null, 1, 3, 4, 2, -1]

解释:
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(); // 返回 1 -> [4, 3, 2]
q.popMiddle(); // 返回 3 -> [4, 2]
q.popMiddle(); // 返回 4 -> [2]
q.popBack(); // 返回 2 -> []
q.popFront(); // 返回 -1 -> [] (队列为空)

实现

通过两个双端队列进行实现,通过比较两个队列的大小来控制

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
84
85
86
87
88
89
90
class FrontMiddleBackQueue {
public:
FrontMiddleBackQueue() {

}

void pushFront(int val) {
left.push_front(val);
if (left.size() == right.size() + 2) {
right.push_front(left.back());
left.pop_back();
}
}

void pushMiddle(int val) {
if (left.size() == right.size() + 1) {
right.push_front(left.back());
left.pop_back();
}
left.push_back(val);
}

void pushBack(int val) {
right.push_back(val);
if (left.size() + 1 == right.size()) {
left.push_back(right.front());
right.pop_front();
}
}

int popFront() {
if (left.empty()) {
return -1;
}
int val = left.front();
left.pop_front();
if (left.size() + 1 == right.size()) {
left.push_back(right.front());
right.pop_front();
}
return val;
}

int popMiddle() {
if (left.empty()) {
return -1;
}
int val = left.back();
left.pop_back();
if (left.size() + 1 == right.size()) {
left.push_back(right.front());
right.pop_front();
}
return val;
}

int popBack() {
if (left.empty()) {
return -1;
}
int val = 0;
if (right.empty()) {
val = left.back();
left.pop_back();
} else {
val = right.back();
right.pop_back();
if (left.size() == right.size() + 2) {
right.push_front(left.back());
left.pop_back();
}
}
return val;
}
private:
deque<int> left;
deque<int> right;
};


/**
* Your FrontMiddleBackQueue object will be instantiated and called as such:
* FrontMiddleBackQueue* obj = new FrontMiddleBackQueue();
* obj->pushFront(val);
* obj->pushMiddle(val);
* obj->pushBack(val);
* int param_4 = obj->popFront();
* int param_5 = obj->popMiddle();
* int param_6 = obj->popBack();
*/