-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1670.design-front-middle-back-queue.cpp
111 lines (102 loc) · 2.31 KB
/
1670.design-front-middle-back-queue.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* @lc app=leetcode id=1670 lang=cpp
*
* [1670] Design Front Middle Back Queue
*/
// @lc code=start
class FrontMiddleBackQueue
{
list<int> data;
list<int>::iterator mid;
int size;
public:
FrontMiddleBackQueue() : size{0}, mid{nullptr} {}
void pushFront(int val)
{
data.push_front(val);
if (size == 0)
mid = data.begin();
else if (size % 2 == 1)
mid = prev(mid);
size++;
}
void pushMiddle(int val)
{
if (size == 0)
{
data.push_back(val);
mid = data.begin();
}
else if (size % 2 == 0)
{
data.insert(next(mid), val);
mid = next(mid);
}
else
{
data.insert(mid, val);
mid = prev(mid);
}
size++;
}
void pushBack(int val)
{
data.push_back(val);
if (size == 0)
mid = data.begin();
else if (size % 2 == 0)
mid = next(mid);
size++;
}
int popFront()
{
if (size == 0)
return -1;
int val = data.front();
if (size % 2 == 0)
mid = next(mid);
data.pop_front();
size--;
return val;
}
int popMiddle()
{
if (size == 0)
return -1;
int val = *mid;
//* after delete the node, the itr point to it is also gone,
//* do we need to record the next mid before erase it
auto mid_new = mid;
if (size % 2 == 1)
mid_new = prev(mid);
else
mid_new = next(mid);
data.erase(mid);
size--;
mid = mid_new;
return val;
}
int popBack()
{
if (size == 0)
return -1;
int val = data.back();
//* must before pop, what if the list only has single node?
if (size % 2 == 1)
mid = prev(mid);
data.pop_back();
size--;
return val;
}
};
/**
* 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();
*/
// @lc code=end