循环链队列的入队和出队,c语言代码
时间: 2023-11-04 20:10:46 浏览: 100
好的,循环链队列的入队和出队操作C语言代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node* next;
} Node;
typedef struct queue {
Node* front;
Node* rear;
int capacity;
int size;
} CircularQueue;
CircularQueue* create_queue(int capacity) {
CircularQueue* queue = (CircularQueue*)malloc(sizeof(CircularQueue));
queue->front = NULL;
queue->rear = NULL;
queue->capacity = capacity;
queue->size = 0;
return queue;
}
int is_empty(CircularQueue* queue) {
return queue->front == NULL;
}
int is_full(CircularQueue* queue) {
return queue->size == queue->capacity;
}
void enqueue(CircularQueue* queue, int value) {
if (is_full(queue)) {
printf("Queue is full\n");
return;
}
Node* node = (Node*)malloc(sizeof(Node));
node->value = value;
if (is_empty(queue)) {
node->next = node;
queue->front = node;
queue->rear = node;
} else {
node->next = queue->rear->next;
queue->rear->next = node;
queue->rear = node;
}
queue->size++;
}
int dequeue(CircularQueue* queue) {
if (is_empty(queue)) {
printf("Queue is empty\n");
return -1;
}
Node* node = queue->front;
int value = node->value;
if (queue->front == queue->rear) {
queue->front = NULL;
queue->rear = NULL;
} else {
queue->front = queue->front->next;
queue->rear->next = queue->front;
}
free(node);
queue->size--;
return value;
}
int main() {
CircularQueue* queue = create_queue(5);
enqueue(queue, 1);
enqueue(queue, 2);
enqueue(queue, 3);
printf("%d\n", dequeue(queue));
printf("%d\n", dequeue(queue));
enqueue(queue, 4);
enqueue(queue, 5);
enqueue(queue, 6);
printf("%d\n", dequeue(queue));
printf("%d\n", dequeue(queue));
printf("%d\n", dequeue(queue));
printf("%d\n", dequeue(queue));
printf("%d\n", dequeue(queue));
return 0;
}
```
这里采用了C语言实现,使用了结构体和指针的概念。其中,`Node`结构体表示链表节点,`CircularQueue`结构体表示循环链队列。成员变量`front`和`rear`分别表示队头和队尾节点的位置,成员变量`capacity`和`size`分别表示队列的容量和当前元素个数。在入队操作中,如果队列已满,则输出错误提示;否则,创建新的节点,并根据队列是否为空进行相应的操作。在出队操作中,如果队列为空,则输出错误提示;否则,删除队头节点,并根据队列中元素个数进行相应的操作。
阅读全文