编写可伸缩循环队列的源代码,并保存为一个或多个源文件
时间: 2024-02-23 13:58:59 浏览: 59
好的,以下是一个可伸缩循环队列的源代码,分为头文件和实现文件两部分:
**queue.h**
```c++
#ifndef QUEUE_H
#define QUEUE_H
#include <stddef.h>
typedef struct {
void** data;
size_t front;
size_t rear;
size_t capacity;
} Queue;
Queue* queue_create(size_t capacity);
void queue_destroy(Queue* queue);
int queue_is_empty(Queue* queue);
int queue_is_full(Queue* queue);
int queue_enqueue(Queue* queue, void* element);
void* queue_dequeue(Queue* queue);
#endif
```
**queue.c**
```c++
#include <stdlib.h>
#include "queue.h"
#define INITIAL_CAPACITY 10
Queue* queue_create(size_t capacity) {
Queue* queue = (Queue*)malloc(sizeof(Queue));
if (queue == NULL) {
return NULL;
}
queue->data = (void**)malloc(sizeof(void*) * capacity);
if (queue->data == NULL) {
free(queue);
return NULL;
}
queue->front = 0;
queue->rear = 0;
queue->capacity = capacity;
return queue;
}
void queue_destroy(Queue* queue) {
free(queue->data);
free(queue);
}
int queue_is_empty(Queue* queue) {
return queue->front == queue->rear;
}
int queue_is_full(Queue* queue) {
return (queue->rear + 1) % queue->capacity == queue->front;
}
int queue_enqueue(Queue* queue, void* element) {
if (queue_is_full(queue)) {
void** new_data = (void**)malloc(sizeof(void*) * queue->capacity * 2);
if (new_data == NULL) {
return 0;
}
size_t i, j;
for (i = queue->front, j = 0; i != queue->rear; i = (i + 1) % queue->capacity, j++) {
new_data[j] = queue->data[i];
}
free(queue->data);
queue->data = new_data;
queue->front = 0;
queue->rear = j;
queue->capacity *= 2;
}
queue->data[queue->rear] = element;
queue->rear = (queue->rear + 1) % queue->capacity;
return 1;
}
void* queue_dequeue(Queue* queue) {
if (queue_is_empty(queue)) {
return NULL;
}
void* element = queue->data[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
return element;
}
```
这个队列可以动态地增加容量,因此可以根据需要存储任意数量的元素。
阅读全文