用C语言表示字符队列代码
时间: 2024-05-13 08:15:45 浏览: 6
以下是一个简单的基于数组实现的字符队列代码示例,供参考:
```c
#define MAX_SIZE 100
// 定义字符队列结构体
typedef struct {
char data[MAX_SIZE];
int front, rear;
} CharQueue;
// 初始化队列
void initQueue(CharQueue *queue) {
queue->front = 0;
queue->rear = 0;
}
// 判断队列是否为空
int isEmpty(CharQueue *queue) {
return queue->front == queue->rear;
}
// 判断队列是否已满
int isFull(CharQueue *queue) {
return queue->rear == MAX_SIZE;
}
// 入队操作
void enqueue(CharQueue *queue, char c) {
if (isFull(queue)) {
printf("Queue is full.\n");
return;
}
queue->data[queue->rear++] = c;
}
// 出队操作
char dequeue(CharQueue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return '\0';
}
return queue->data[queue->front++];
}
```
使用示例:
```c
int main() {
CharQueue queue;
initQueue(&queue);
enqueue(&queue, 'a');
enqueue(&queue, 'b');
enqueue(&queue, 'c');
printf("%c\n", dequeue(&queue)); // 输出'a'
printf("%c\n", dequeue(&queue)); // 输出'b'
printf("%c\n", dequeue(&queue)); // 输出'c'
printf("%c\n", dequeue(&queue)); // 输出'Queue is empty.'
return 0;
}
```