R7-5 队列操作

Author Avatar
小包
发表:2024-11-03 04:27:22
修改:2024-11-03 04:27:21

请实现一个MyQueue类,实现出队,入队,求队列长度.

实现入队函数 void push(int x);
实现出队函数 int pop();
实现求队列长度函数 int size();

输入格式:

每个输入包含1个测试用例。每个测试用例第一行给出一个正整数 n (n <= 10^6) ,接下去n行每行一个数字,表示一种操作:
1 x : 表示从队尾插入x,0<=x<=2^31-1。
2 : 表示队首元素出队。
3 : 表示求队列长度。

输出格式:

对于操作2,若队列为空,则输出 “Invalid”,否则请输出队首元素。 对于操作3,请输出队列长度。
每个输出项最后换行。

输入样例:

5
3
2
1 100
3
2

输出样例:

0
Invalid
1
100
#include <bits/stdc++.h>
using namespace std;

// 定义 MyQueue 类
class MyQueue {
private:
    vector<int> data; // 存储队列元素
    int head;         // 队首指针

public:
    // 构造函数,初始化队首指针
    MyQueue() : head(0) {}

    // 入队操作,将元素 x 加入队尾
    void push(int x) {
        data.push_back(x);
    }

    // 出队操作,尝试移除并返回队首元素
    // 如果队列为空,返回一个标志值
    int pop() {
        if (head >= data.size()) {
            return INT32_MIN; // 使用最小整数作为无效标志
        }
        return data[head++];
    }

    // 获取当前队列的长度
    int size() const {
        return data.size() - head;
    }
};

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    
    int n;
    cin >> n;
    MyQueue q;
    string output; // 用于缓存所有输出

    while(n--){
        int cmd;
        cin >> cmd;
        if(cmd == 1){
            int x;
            cin >> x;
            q.push(x);
        }
        else if(cmd == 2){
            int res = q.pop();
            if(res == INT32_MIN){
                output += "Invalid\n";
            }
            else{
                output += to_string(res) + "\n";
            }
        }
        else if(cmd == 3){
            output += to_string(q.size()) + "\n";
        }
    }

    // 输出所有结果
    cout << output;
}

评论