用100个数组存储数据,每来新的数据,按位从第1个数组存到第100个数组,数据长度超过100的舍弃多余的,请用C语言环形队列实现
时间: 2024-10-07 08:02:06 浏览: 52
在C语言中,我们可以使用数组和索引来模拟一个环形队列。由于需要对数据进行轮转存储,当新数据到来并且数组已满时,我们需要将最后一个元素替换掉第一个位置的数据,形成一个循环。下面是一个简单的实现:
```c
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int front; // 队头元素的索引
int rear; // 队尾元素的索引 + 1 (因为是环形)
} Queue;
// 初始化队列
void initQueue(Queue *queue) {
queue->front = -1;
queue->rear = -1;
}
// 插入数据,如果队列已满则移除旧数据
void enqueue(Queue *queue, int value) {
if ((queue->rear + 1) % MAX_SIZE == queue->front) { // 队列已满
printf("Warning: Queue is full, discarding old data.\n");
queue->data[queue->front] = value;
queue->front = (queue->front + 1) % MAX_SIZE; // 移动队头指针
} else {
queue->rear = (queue->rear + 1) % MAX_SIZE; // 更新队尾指针
queue->data[queue->rear] = value; // 存储新值
}
}
// 取出数据
int dequeue(Queue *queue) {
if (queue->front == queue->rear) { // 空队列
return -1; // 返回错误码或特殊值表示空
} else {
int removedValue = queue->data[queue->front]; // 保存并移除队头值
queue->front = (queue->front + 1) % MAX_SIZE; // 移动队头指针
return removedValue;
}
}
// 主函数示例
int main() {
Queue myQueue;
initQueue(&myQueue);
for (int i = 1; i <= 150; ++i) { // 模拟数据插入过程
enqueue(&myQueue, i);
if (i > 100) break; // 如果超过100,不再添加
}
while (queue->front != queue->rear) { // 取出直到队列为空
printf("%d ", dequeue(&myQueue));
}
return 0;
}
```
这个程序首先初始化一个环形队列,并在`enqueue`函数中处理新数据插入。如果队列满了,会丢弃旧数据并移动队头指针。`dequeue`函数用于取出队首的数据。
注意,这里假设了队列溢出时只警告并不会导致程序崩溃。在实际应用中,你可能会选择更复杂的策略来处理这种情况。同时,这个实现并未包含错误检查,例如插入前检查队列是否已满等。在生产环境中,你应该完善这些细节。
阅读全文
相关推荐


















