#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define SIZE 5
// 数据域
typedef struct LData {
char c; // 常数
} LData;
// 顺序表实现循环队列
typedef struct Queue {
LData data[SIZE]; //数据域
int front, rear;
} Queue;
//入队 队头出,队尾入
void pushQ(Queue *s, char e) {
if ((s->rear - s->front + 1 + SIZE) % SIZE == 0) {
printf("队列已满\n");
return;
}
s->data[s->rear].c = e; // 队尾插入 队尾指针+1,队尾始终为空
s->rear = (s->rear + 1) % SIZE;
s->data[s->rear].c = '0';
}
// 出队
void popQ(Queue *s) {
if (s->rear == s->front) {
printf("队列为空\n");
return;
}
printf("出队元素是:%c\n", s->data[s->front].c);
s->front = (s->front + 1) % SIZE;
}
// 清空队列
void clearQ(Queue *s) {
s->front = s->rear = 0;
}
//获取队列的长度
void getQLength(Queue *s) {
printf("队列的长度为:%d\n", (s->rear - s->front + SIZE) % SIZE);
}
int main() {
// 初始化队列 顺序表实现,在顺序表中空一个元素
Queue *q;
q = (Queue *) malloc(sizeof(Queue));
q->front = q->rear = 0;
//测试
pushQ(q, 'a');
pushQ(q, 'b');
popQ(q);
pushQ(q, 'c');
pushQ(q, 'd');
popQ(q);
getQLength(q);
pushQ(q, 'e');
popQ(q);
pushQ(q, 'f');
pushQ(q, 'g');
getQLength(q);
popQ(q);
popQ(q);
popQ(q);
popQ(q);
popQ(q);
return 0;
}
顺序表实现队列的创建,入队,出队,队列的长度,清空队列
最新推荐文章于 2024-11-13 19:36:04 发布