C++
#include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; int q[100000]; int idx=-1; // 采取 head rear 更好 while (n--) { string op; cin >> op; if (op=="push") cin >> q[++idx]; else if (op=="front" && idx > -1) cout << q[0] << endl; else if (op=="pop" && idx > -1) { cout << q[0] << endl; for (int i=0; i<idx; i++) { q[i] = q[i+1]; } idx--; } else cout << "error" << endl; } return 0; } // 64 位输出请用 printf("%lld")
写成类
#include <iostream> #include <vector> using namespace std; class queue { private: int x[100000]; int head=0, rear=0; public: int isEmpty() { return head==rear; } void push(int i) { x[rear++] = i; } int pop() { return x[head++]; } int front() { return x[head]; } }; int main() { int n; cin >> n; queue q; string op; int a; while (n--) { cin >> op; if (op=="push") { cin >> a; q.push(a); } else if (op=="front" && !q.isEmpty()) { cout << q.front() << endl; } else if (op=="pop" && !q.isEmpty()) { cout << q.front() << endl; q.pop(); } else { cout << "error" << endl; } } return 0; } // 64 位输出请用 printf("%lld")