C语言中如何实现循环队列?
时间: 2024-06-14 22:03:44 浏览: 12
C语言中实现循环队列的方法如下:
1.定义一个结构体来表示循环队列,包括队列的大小、队首和队尾指针以及存储元素的数组。
```c
typedef struct {
int* arr; // 存储元素的数组
int front; // 队首指针
int rear; // 队尾指针
int count; // 队列中元素的个数
int N; // 队列的大小
} MyCircularQueue;
```
2.创建循环队列的函数,需要动态分配内存空间,并初始化队列的各个参数。
```c
MyCircularQueue* myCircularQueueCreate(int k) {
MyCircularQueue* q = (MyCircularQueue*)malloc(sizeof(MyCircularQueue)); // 申请空间
if (q == NULL) {
return NULL;
}
q->arr = (int*)malloc(sizeof(int) * k); // 申请空间
if (q->arr == NULL) {
return NULL;
}
q->front = 0; // 初始化
q->rear = 0;
q->count = 0;
q->N = k;
return q;
}
```
3.判断队列是否为空的函数,当队列中元素个数为0时,队列为空。
```c
bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
return obj->count == 0;
}
```
4.判断队列是否已满的函数,当队列中元素个数等于队列大小时,队列已满。
```c
bool myCircularQueueIsFull(MyCircularQueue* obj) {
return obj->count == obj->N;
}
```
5.向队列中插入元素的函数,需要先判断队列是否已满,如果已满则插入失败,否则将元素插入队尾。
```c
bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
if (myCircularQueueIsFull(obj)) {
return false;
}
obj->arr[obj->rear] = value;
obj->rear = (obj->rear + 1) % obj->N;
obj->count++;
return true;
}
```
6.从队列中删除元素的函数,需要先判断队列是否为空,如果为空则删除失败,否则将队首元素删除。
```c
bool myCircularQueueDeQueue(MyCircularQueue* obj) {
if (myCircularQueueIsEmpty(obj)) {
return false;
}
obj->front = (obj->front + 1) % obj->N;
obj->count--;
return true;
}
```
7.获取队首元素的函数,需要先判断队列是否为空,如果为空则返回-1,否则返回队首元素。
```c
int myCircularQueueFront(MyCircularQueue* obj) {
if (myCircularQueueIsEmpty(obj)) {
return -1;
}
return obj->arr[obj->front];
}
```
8.获取队尾元素的函数,需要先判断队列是否为空,如果为空则返回-1,否则返回队尾元素。
```c
int myCircularQueueRear(MyCircularQueue* obj) {
if (myCircularQueueIsEmpty(obj)) {
return -1;
}
return obj->arr[(obj->rear - 1 + obj->N) % obj->N];
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)