当前位置:   article > 正文

数据结构循环队列的实现_已知循环队列的结构定义如下: typedef struct { int size, front, r

已知循环队列的结构定义如下: typedef struct { int size, front, rear; int *ele

循环队列的实现

代码如下:

#include<iostream>
using namespace std;//使用标准库,作用防止重名的干扰
typedef int ElemType;//就是自定义一个类型名ElemType
typedef int Status;//自定义类型的语句。
//循环队列结构体定义
typedef struct{
    int front;//前
    int rear;//后
    int maxSize;       //最大存储量
    ElemType *element;  //首地址
}Queue;

//创建一个能容纳mSize的队列
void Create(Queue *Q,int maxSize){
    Q->maxSize=maxSize;
    Q->element=(ElemType *)malloc(sizeof(ElemType)*maxSize);
    Q->front=Q->rear=0;
}

//销毁一个已经存在的队列,释放队列占用的空间
void Destroy(Queue *Q){
    Q->maxSize=-1;
    free(Q->element);
    Q->front=Q->rear=-1;
}

//判断是否为空
bool isEmpty(Queue *Q){//bool表示布尔型变量
    return Q->front==Q->rear;
}

bool isFull(Queue *Q){
    return (Q->rear+1)%(Q->maxSize)==Q->front;
}

//获取头元素,通过x返回
bool Front(Queue *Q,ElemType *x){
    if(isEmpty(Q))
        return false;
    *x=Q->element[(Q->front+1)%(Q->maxSize)];
    return true;
}

//进队操作,在对尾插入x
bool EnQueue(Queue *Q,ElemType x){
    if(isFull(Q))
        return false;
    Q->rear=(Q->rear+1)%Q->maxSize;
    Q->element[Q->rear]=x;
    return true;
}

//出队操作
bool Dequeue(Queue *Q){
    if(isEmpty(Q))
        return false;
    Q->front=(Q->front+1)%Q->maxSize;
    return true;
}

//清除队列中全部元素
void Clear(Queue *Q){
    Q->front=Q->rear=0;
}

int main(){
    int x,y;
    Queue q;
    Create(&q,10);
    for(int i=0;i<10;i++){
        EnQueue(&q,i);
    }
    Front(&q,&x);
    cout<<"队头元素: "<<x<<endl;
    cout<<"队列元素: ";
    for(int j=0;j<9;j++){
        Front(&q,&y);
        cout<<y<<" ";
        Dequeue(&q);
    }
    cout<<endl;
    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84

运行结果如下:
在这里插入图片描述
欢迎您关注我的微信公众号:学习微站(studysth)在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/515601
推荐阅读
  

闽ICP备14008679号