用C语言写一份向环形队列中增加字符串,并输出
时间: 2024-12-02 18:14:06 浏览: 50
在C语言中,我们可以创建一个环形队列结构来存储字符串并支持添加和输出操作。首先,我们需要定义一个动态数组作为队列的基础数据结构,同时维护两个指针,一个指向当前元素的位置(front),另一个指向下一个待插入位置(rear)。以下是简单的环形队列结构以及实现字符串添加和输出的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 10 // 环形队列的最大容量
typedef struct {
char *queue[MAX_SIZE]; // 队列元素
int front; // 队头指针
int rear; // 队尾指针
} Queue;
// 添加字符串到队列
void enqueue(Queue *q, const char *str) {
if ((q->rear + 1) % MAX_SIZE == q->front) { // 判断是否已满
printf("Queue is full.\n");
return;
}
q->queue[q->rear] = strdup(str); // 使用strdup复制字符串并存入队列
q->rear = (q->rear + 1) % MAX_SIZE; // 更新队尾指针
}
// 输出队列中的字符串(如果非空)
void dequeue(Queue *q) {
if (q->front == q->rear) { // 如果队列为空
printf("Queue is empty.\n");
} else {
printf("Current string in the queue: %s\n", q->queue[q->front]);
free(q->queue[q->front]); // 释放内存
q->front = (q->front + 1) % MAX_SIZE; // 更新队头指针
}
}
int main() {
Queue my_queue;
my_queue.front = my_queue.rear = -1; // 初始化指针
// 添加字符串示例
enqueue(&my_queue, "Hello");
enqueue(&my_queue, "World");
// 输出字符串示例
dequeue(&my_queue);
return 0;
}
```
阅读全文
相关推荐








