考研C语言数据结构-循环队列
#include <stdio.h>
#include <stdlib.h>
#define maxSize 6
// 定义循环队列数据类型
typedef struct {
int data[maxSize];
int front;// 队头指针
int rear;// 队尾指针 ---> 指向队尾元素的下一个位置 ---> 区分对空与满条件
}CQueue;
void initCQueue(CQueue &Q) {
Q.front = Q.rear = 0;
}
// 判断队空
bool isEmpty(CQueue Q) {
if(Q.front == Q.rear)
return true;
return false;
}
// 入队 <--- 队尾
bool enQueue(CQueue &Q, int e) {
// 判断队列是否已满
if((Q.rear + 1) % maxSize == Q.front)
return false;
Q.data[Q.rear] = e;
Q.rear = (Q.rear + 1) % maxSize;
return true;
}
// 出队 <--- 队头
bool deQueue(CQueue &Q, int &e) {
// 判断队列是否为空
if(isEmpty(Q))
return false;
e = Q.data[Q.front];
Q.front = (Q.front + 1) % maxSize;
return true;
}
// 查询队头元素
bool getHead(CQueue &Q, int &e) {
if(isEmpty(Q))
return false;
e = Q.data[Q.front];
return true;
}
// 获取队列长度
int getLength(CQueue Q) {
return (Q.rear + maxSize - Q.front) % maxSize;
}
int main(void) {
CQueue Q;
initCQueue(Q);
enQueue(Q, 1);
enQueue(Q, 2);
enQueue(Q, 3);
int length = getLength(Q);
printf("此时队列长度:%d\n", length);
enQueue(Q, 4);
enQueue(Q, 5);
if(!enQueue(Q, 6)){
printf("队列已满,无法入队。\n");
}
int e = -1;
deQueue(Q, e);
printf("出队元素:%d\n", e);
deQueue(Q, e);
printf("出队元素:%d\n", e);
deQueue(Q, e);
printf("出队元素:%d\n", e);
deQueue(Q, e);
printf("出队元素:%d\n", e);
deQueue(Q, e);
printf("出队元素:%d\n", e);
system("pause");
return 0;
}
分类:
C语言数据结构
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端