循环队列的基本操作

本文介绍了如何使用C++实现一个循环队列的数据结构,包括初始化、入队、出队、获取队头元素等操作,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * @author:qq_45671732
 * @version:1.0
 */
#include "bits/stdc++.h"

using namespace std;

#define OK 0
#define ERROR -1
#define MAXQSIZE 100

typedef struct {
    int *base;
    int front;
    int rear;
} SqQueue;

int InitQueue(SqQueue &Q) {
    //队列初始化
    Q.base = new int[MAXQSIZE];
    if (Q.base == NULL) {
        cerr << "队列初始化失败" << endl;
        return ERROR;
    } else {
        Q.front = Q.rear = 0;
        cout << "队列初始化成功" << endl;
        return OK;
    }
}

int QueueLength(SqQueue Q) {
    //返回队列的长度
    return ((Q.rear - Q.front + MAXQSIZE) % MAXQSIZE);
}

int EnQueue(SqQueue &Q, int e) {
    //入队
    if ((Q.rear + 1) % MAXQSIZE == Q.front) {
        cerr << "循环队列已经满了,入队失败" << endl;
        return ERROR;
    } else {
        Q.base[Q.rear] = e;
        Q.rear = (Q.rear + 1) % MAXQSIZE;
        cout << "入队成功" << endl;
        return OK;
    }
}

int DeQueue(SqQueue &Q) {
    //出队
    if (Q.front == Q.rear) {
        cerr << "队空,出队失败" << endl;
        return ERROR;
    } else {
        Q.front = (Q.front + 1) % MAXQSIZE;
        cout << "出队成功" << endl;
        return OK;
    }
}

int GetHead(SqQueue Q) {
    //取队头元素
    if (Q.front != Q.rear) {
        return Q.base[Q.front];
    }
}

int main() {
    SqQueue Q;
    InitQueue(Q);
    int choice;
    do {
        cout << "1.入队" << endl;
        cout << "2.出队" << endl;
        cout << "3.取队头元素" << endl;
        cout << "4.队列长度" << endl;
        cout << "************************" << endl;
        cout << "请输入您的选择:" << endl;
        cin >> choice;
        switch (choice) {
            case 1: {
                int e;
                cout << "请输入您要入队的元素:" << endl;
                cin >> e;
                EnQueue(Q, e);
                break;
            }
            case 2: {
                DeQueue(Q);
                break;
            }
            case 3: {
                int res;
                res = GetHead(Q);
                cout << "队头元素为:" << res << endl;
                break;
            }
            case 4: {
                int length = QueueLength(Q);
                cout << "队列的长度为:" << length << endl;
                break;
            }
            default: {
                exit(ERROR);
            }
        }
    } while (1);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_45671732

你们鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值