数据结构-循环队列

#include<bits/stdc++.h>
using namespace std;
#define MAXSIZE 10

//注意:对于循环队列来说,为了区别空或者满,不得不永远浪费一个空间,也就是front所在的位置。

typedef struct MyQueue {
    //头指针和尾指针
    int data[MAXSIZE];
    int front;
    int rear;
}MyQueue;

//循环队列的创建
MyQueue* create(){
    MyQueue* myQueue = (MyQueue*) malloc(sizeof (MyQueue));
    myQueue->front = 0;
    myQueue->rear = 0;
    return myQueue;
}
bool isEmpty(MyQueue* myQueue) {
    if(myQueue->front == myQueue->rear) {
        return true;
    }else {
        return false;
    }
}
//入队
bool push(MyQueue* myQueue, int num) {
    //第一步:判断队列是否已满
    if((myQueue->rear+1)%MAXSIZE == myQueue->front) {
        return false;
    }
    //判断后入队,先将尾指针加一再放入数据
    myQueue->rear = (myQueue->rear+1)%MAXSIZE;
    myQueue->data[myQueue->rear] = num;
    return true;
}
//出队
bool pop(MyQueue* myQueue) {
    //第一步:判断是否为空
    if(isEmpty(myQueue)) {
        return false;
    }
    //如果非空,则可以进行删除
    myQueue->data[myQueue->front] = 0;
    myQueue->front = (myQueue->front+1)%MAXSIZE;
    return true;
}
//遍历
bool traverse(MyQueue* myQueue) {
    //第一步:判断是否为空
    if(isEmpty(myQueue)) {
        return false;
    }
    int i = myQueue->front;
    while (i!=myQueue->rear) {
        //记住:front位置上为空
        i = (i+1)%MAXSIZE;
        cout << myQueue->data[i] << " ";
    }
    cout << endl;
}
int main() {
    MyQueue* myQueue = create();
    cout << "请输入您要插入的数据个数:";
    int n, num;
    cin >> n;
    cout << "请输入数据:";
    for(int i=0; i<n; i++) {
        cin >> num;
        push(myQueue, num);
    }
    traverse(myQueue);
    pop(myQueue);
    traverse(myQueue);
    pop(myQueue);
    traverse(myQueue);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

NCU-wfb

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

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

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

打赏作者

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

抵扣说明:

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

余额充值