linux c实现队列存放特定长度为6的字符和取出,可以存放100组
时间: 2023-12-10 14:42:36 浏览: 34
下面是一个基于数组实现的队列存放特定长度为6的字符和取出的 C 语言程序。该程序可以存放100组字符,当队列满时,新的字符将无法入队。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define QUEUE_SIZE 100 // 队列最大容量
#define STR_LEN 6 // 字符串长度
// 队列结构体
typedef struct {
char data[STR_LEN + 1]; // 存放字符串的数组,多留一个字节存放 '\0'
int front; // 队头指针
int rear; // 队尾指针
} Queue;
// 初始化队列
void initQueue(Queue *queue) {
queue->front = queue->rear = 0;
}
// 判断队列是否为空
int isQueueEmpty(Queue *queue) {
return queue->front == queue->rear;
}
// 判断队列是否已满
int isQueueFull(Queue *queue) {
return (queue->rear + 1) % QUEUE_SIZE == queue->front;
}
// 入队
void enqueue(Queue *queue, const char *str) {
if (isQueueFull(queue)) {
printf("Queue is full, cannot enqueue.\n");
return;
}
strncpy(queue->data[queue->rear], str, STR_LEN);
queue->rear = (queue->rear + 1) % QUEUE_SIZE;
}
// 出队
void dequeue(Queue *queue, char *str) {
if (isQueueEmpty(queue)) {
printf("Queue is empty, cannot dequeue.\n");
return;
}
strncpy(str, queue->data[queue->front], STR_LEN);
queue->front = (queue->front + 1) % QUEUE_SIZE;
}
int main() {
Queue queue;
initQueue(&queue);
// 入队
enqueue(&queue, "abcdef");
enqueue(&queue, "ghijkl");
enqueue(&queue, "mnopqr");
// 出队
char str[STR_LEN + 1];
dequeue(&queue, str);
printf("Dequeued: %s\n", str);
dequeue(&queue, str);
printf("Dequeued: %s\n", str);
dequeue(&queue, str);
printf("Dequeued: %s\n", str);
dequeue(&queue, str); // 队列已空,无法出队
return 0;
}
```
注意:上述代码只是一个简单的示例,实际应用时需要考虑更多的情况,例如队列溢出、队列为空时的处理等。