数据结构之队列

队列

  • 线性存储结构,队列的一边进行删除操作,另外一边进行插入操作(双端队列除外);
  • 一般是队头出队(删除),队尾入队(插入);
  • 先进先出
  • 存储结构可以为顺序结构,也可以为链式结构;
  • 类别:顺序队列、链式队列、循环队列、双端队列

循环队列数据结构 C语言

//循环队列数据结构
#define true	1
#define false	0
#define OVERFLOW 1

#define MAXQSIZE 100
typedef struct{
    int* base; //初始化的动态分配存储空间
    int front; //队头指针
    int rear; //队尾指针
}SqQueue;

循环队列方法声明和实现 C语言

  • 基本函数声明
void InitQueue(SqQueue*);
//构造一个空的队列
int QueueLength(SqQueue);
//返回队列长度
void EnQueue(SqQueue*, int);
//入队
void DeQueue(SqQueue*, int*);
//出队
void DestoryQueue(SqQueue*);
//销毁队列
int QueueEmpty(SqQueue);
//队空判断
  • 基本函数实现
void InitQueue(SqQueue* Q){ //构造一个空的队列
    Q->base = (int*)malloc(MAXQSIZE * sizeof(int));
    if(!Q->base) return exit(OVERFLOW);
    Q->front = Q->rear = 0;
}

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

void EnQueue(SqQueue* Q, int e){ //入队、插入
    if((Q->rear + 1) % MAXQSIZE == Q->front) return exit(OVERFLOW); //队满
    Q->base[Q->rear] = e;
    Q->rear = (Q->rear + 1) % MAXQSIZE;
}

void DeQueue(SqQueue* Q, int* e){ //出队、删除
    if(Q->front == Q->rear) return exit(OVERFLOW); //队空
    *e = Q->base[Q->front]; //e是指针,修改指针e指向地址空间的值,需要对*e进行赋值
    Q->front = (Q->front + 1) % MAXQSIZE;
}

void DestoryQueue(SqQueue* Q){ //销毁队列
    free(Q->base);
    free(Q);
}

int QueueEmpty(SqQueue Q){ //判队列是否为空
    if(Q.front == Q.rear) return true;
    return false;
}
  • 循环队列操作的例子
int main(){
    int* e = (int*)calloc(1, sizeof(int));
    SqQueue* Q = (SqQueue*)malloc(sizeof(SqQueue));

    InitQueue(Q);
    EnQueue(Q, 21);
    EnQueue(Q, 23);
    printf("%d\n", QueueLength(*Q)); //2
    DeQueue(Q, e);
    printf("%d\n", *e); //21
    printf("%d\n", QueueLength(*Q)); //1
    DeQueue(Q, e);
    printf("%d\n", *e); //23

    DestoryQueue(Q);
    free(e);
    return 0;
}

输出结果为
2
21
1
23

参照

严蔚敏 吴伟名 米宁.数据结构(C语言版)[M].出版地:北京 出版社:清华大学出版社,出版年∶2018.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值