很显然题目是想我们实现一个队列,那么直接调用STL库就十分的没有味道了。
我的方案是用一个链表来模拟队列,链表含队首指针和队尾指针(仅有队首指针会超时!),push是在队尾添加节点的操作,pop是在队首删除节点的操作,front是输出队首节点的操作。
#include <iostream>
#include <string>
using namespace std;
class node {
public:
int x;
node* pnext = nullptr;
node(int x) {
this->x = x;
}
};
class queue {
private:
node* pfront = nullptr; // 队首指针
node* prear = nullptr; // 队尾指针
public:
void push(int x) {
node* tmp = new node(x);
if (pfront == nullptr) {
pfront = tmp;
prear = tmp;
} else {
prear->pnext = tmp;
prear = tmp;
}
}
void pop() {
if (pfront == nullptr)
cout << "error" << endl;
else {
cout << pfront->x << endl;
if (pfront == prear) {
free(pfront);
pfront = nullptr;
prear = nullptr;
} else {
node* tmp = pfront;
pfront = pfront->pnext;
free(tmp);
}
}
}
void front() {
if (pfront == nullptr)
cout << "error" << endl;
else
cout << pfront->x << endl;
}
};
int main() {
int n;
cin >> n;
queue q;
for (int i = 0; i < n; i++) {
string op;
cin >> op;
if (op == "push") {
int x;
cin >> x;
q.push(x);
} else if (op == "pop") {
q.pop();
} else if (op == "front") {
q.front();
}
}
return 0;
}