设队列的元素类型为char,实现顺序循环队列的各种基本操作的c语言程序
时间: 2023-06-03 22:04:00 浏览: 92
好的,以下是一个基本的顺序循环队列的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define QUEUE_SIZE 100 // 队列的最大容量为100
typedef struct {
char data[QUEUE_SIZE]; // 队列中的元素
int front; // 队头指针
int rear; // 队尾指针
} Queue;
/* 初始化队列 */
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
/* 判断队列是否为空 */
int isQueueEmpty(Queue *q) {
return q->front == q->rear;
}
/* 判断队列是否已满 */
int isQueueFull(Queue *q) {
return (q->rear + 1) % QUEUE_SIZE == q->front;
}
/* 入队 */
int enqueue(Queue *q, char c) {
if (isQueueFull(q)) {
printf("队列已满,无法入队!\n");
return 0;
} else {
q->data[q->rear] = c;
q->rear = (q->rear + 1) % QUEUE_SIZE; // 循环队列的实现
return 1;
}
}
/* 出队 */
int dequeue(Queue *q, char *c) {
if (isQueueEmpty(q)) {
printf("队列已空,无法出队!\n");
return 0;
} else {
*c = q->data[q->front];
q->front = (q->front + 1) % QUEUE_SIZE; // 循环队列的实现
return 1;
}
}
int main() {
Queue q;
initQueue(&q); // 初始化队列
// 往队列中依次添加元素
enqueue(&q, 'a');
enqueue(&q, 'b');
enqueue(&q, 'c');
enqueue(&q, 'd');
enqueue(&q, 'e');
// 依次出队并输出队列中的元素
char c;
while (dequeue(&q, &c)) {
printf("%c ", c);
}
printf("\n");
return 0;
}
```
这个程序实现了顺序循环队列的基本操作,包括初始化队列、判断队列是否为空、判断队列是否已满、入队和出队。其中,循环队列的实现利用了取余运算,让队尾指针在队列的最大容量内循环移动。在这个程序中,我们使用了一个大小为100的字符数组来存储队列中的元素。如果队列已满,就无法再添加元素,如果队列已空,就无法再取出元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)