Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2e29cbf

Browse files
authoredNov 29, 2020
Update 1670.Design-Front-Middle-Back-Queue_v1.cpp
1 parent 42da347 commit 2e29cbf

File tree

1 file changed

+13
-26
lines changed

1 file changed

+13
-26
lines changed
 

‎Linked_List/1670.Design-Front-Middle-Back-Queue/1670.Design-Front-Middle-Back-Queue_v1.cpp

Lines changed: 13 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,45 @@
11
class FrontMiddleBackQueue {
2-
int arr[1000];
3-
int n = 0;
2+
vector<int>q;
43
public:
54
FrontMiddleBackQueue() {
65
}
76

87
void pushFront(int val)
98
{
10-
for (int i=n; i>=1; i--)
11-
arr[i] = arr[i-1];
12-
arr[0] = val;
13-
n++;
9+
q.insert(q.begin(),val);
1410
}
1511

1612
void pushMiddle(int val)
1713
{
18-
int i = n-1;
19-
for (int i=n; i>= max(1,n/2); i--)
20-
arr[i] = arr[i-1];
21-
arr[n/2] = val;
22-
n++;
14+
q.insert(q.begin()+q.size()/2, val);
2315
}
2416

2517
void pushBack(int val)
2618
{
27-
arr[n] = val;
28-
n++;
19+
q.push_back(val);
2920
}
3021

3122
int popFront()
3223
{
33-
if (n==0) return -1;
34-
int ret = arr[0];
35-
for (int i=0; i<n-1; i++)
36-
arr[i] = arr[i+1];
37-
n--;
24+
if (q.empty()) return -1;
25+
int ret = q.front();
26+
q.erase(q.begin());
3827
return ret;
3928
}
4029

4130
int popMiddle()
4231
{
43-
if (n==0) return -1;
44-
int ret = arr[(n-1)/2];
45-
for (int i=(n-1)/2; i<n; i++)
46-
arr[i] = arr[i+1];
47-
n--;
32+
if (q.empty()) return -1;
33+
int ret = *(q.begin()+(q.size()-1)/2);
34+
q.erase(q.begin()+(q.size()-1)/2);
4835
return ret;
4936
}
5037

5138
int popBack()
5239
{
53-
if (n==0) return -1;
54-
int ret = arr[n-1];
55-
n--;
40+
if (q.empty()) return -1;
41+
int ret = q.back();
42+
q.pop_back();
5643
return ret;
5744
}
5845
};

0 commit comments

Comments
 (0)
Please sign in to comment.