Design a queue that supports push
and pop
operations in the front, middle, and back.
Implement the FrontMiddleBack
class:
FrontMiddleBack()
Initializes the queue.void pushFront(int val)
Adds val to the front of the queue.void pushMiddle(int val)
Adds val to the middle of the queue.void pushBack(int val)
Addsval
to the back of the queue.int popFront()
Removes the front element of the queue and returns it. If the queue is empty, return-1
.int popMiddle()
Removes the middle element of the queue and returns it. If the queue is empty, return-1
.int popBack()
Removes the back element of the queue and returns it. If the queue is empty, return-1
.
Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example:
- Pushing
6
into the middle of[1, 2, 3, 4, 5]
results in[1, 2, 6, 3, 4, 5]
. - Popping the middle from
[1, 2, 3, 4, 5, 6]
returns3
and results in[1, 2, 4, 5, 6]
.
Example:
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]
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)
Approach:
C++
#include <bits/stdc++.h>using namespace std;class FrontMiddleBackQueue{deque<int> dq;public:FrontMiddleBackQueue(){dq.clear();}void pushFront(int val){dq.push_front(val);}void pushMiddle(int val){int n = dq.size();dq.insert(dq.begin() + n / 2, val);}void pushBack(int val){dq.push_back(val);}int popFront(){if (dq.empty())return -1;int ans = dq.front();dq.pop_front();return ans;}int popMiddle(){if (dq.empty())return -1;int mid = (dq.size() - 1) / 2;int ans = *(dq.begin() + mid);dq.erase(dq.begin() + mid);return ans;}int popBack(){if (dq.empty())return -1;int ans = dq.back();dq.pop_back();return ans;}};int main(){FrontMiddleBackQueue q;q.pushFront(1);q.pushBack(2);q.pushMiddle(3);q.pushMiddle(4);cout << "[";cout << q.popFront() << ", ";cout << q.popMiddle() << ", ";cout << q.popMiddle() << ", ";cout << q.popBack() << ", ";cout << q.popFront();cout << "]";return 0;}
No comments:
Post a Comment