题解 | 【模板】循环队列
【模板】循环队列
https://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf
C++ 和顺序队列差别挺大,细节处需要多加注意
#include <iostream> using namespace std; class queue { private: int x[100000]; public: int head=0, rear=0; int size=0; int isEmpty() { return head==rear; } int isFull() { return head==(rear+1)%size; } void push(int i) { // x[(rear++)%size] = i; // rear++会超过size x[rear] = i; rear = (rear+1)%size; } void pop() { // return x[]; // head++会超过size head = (head+1)%size; } int front() { return x[head]; } }; int main() { int n, s; cin >> s >> n; string op; int a; queue q; q.size = s+1; // 需要多申请一个空位置 while (n--) { cin >> op; if (op=="push") { cin >> a; if (!q.isFull()) { q.push(a); } else cout << "full" << endl; } else if (op=="pop" && !q.isEmpty()) { cout << q.front() << endl; q.pop(); } else if (op=="front" && !q.isEmpty()) { cout << q.front() << endl; } else { cout << "empty" << endl; } // cout << op << ' ' << q.head << ' ' << q.rear << endl; } } // 64 位输出请用 printf("%lld")