题解 | #【模板】循环队列#

【模板】循环队列

https://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf

#include <iostream>
#include <string>
using namespace std;

const int N = 100010;

int q[N];
int hh = 0, tt = 0;

int main() {
    int size, n;
    cin >> size >> n;

    size++;  // 为了区分队列满与队列空,需要使用 size + 1 的空间

    while (n --) {
        string op;
        cin >> op;  // 读取操作符

        if (op == "push") {
            int x;
            cin >> x;
            // 判断队列是否已满:tt 的下一个位置和 hh 重合则队列满
            if ((tt + 1) % size == hh) {
                cout << "full" << endl;
            } else {
                q[tt] = x;  // 将元素插入队尾
                tt = (tt + 1) % size;  // 更新队尾指针,环形处理
            }
        } else if (op == "front") {
            // 判断队列是否为空:队首与队尾重合
            if (tt == hh) {
                cout << "empty" << endl;
            } else {
                cout << q[hh] << endl;  // 输出队首元素但不移除
            }
        } else if (op == "pop") {
            // 判断队列是否为空:队首与队尾重合
            if (tt == hh) {
                cout << "empty" << endl;
            } else {
                cout << q[hh] << endl;  // 输出并移除队首元素
                hh = (hh + 1) % size;  // 更新队首指针,环形处理
            }
        }
    }

    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
牛客83700679...:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务