1760.设计前中后队列
请你设计一个队列,支持在前,中,后三个位置的 push 和 pop 操作。
请注意当有 两个 中间位置的时候,选择靠前面的位置进行操作。比方说:
示例 1:
提示:
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();
*/
(1) 双端队列。
原文地址:https://blog.csdn.net/qq_56086076/article/details/134675190
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_3450.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!