链式队列设计。以带头结点的循环单链表实现,并只设尾指针,不设头指针。编写实现这种链式队列的初始化,入队列,出队列,判断非空函数,设计一个主函数,进行测试。用c语言
时间: 2023-06-01 15:01:38 浏览: 138
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct {
Node* rear;
} Queue;
// 初始化队列
void initQueue(Queue* q) {
q->rear = NULL;
}
// 判断队列是否为空
int isEmpty(Queue* q) {
return q->rear == NULL;
}
// 入队列
void enqueue(Queue* q, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
if (isEmpty(q)) {
q->rear = newNode;
newNode->next = newNode;
}
else {
newNode->next = q->rear->next;
q->rear->next = newNode;
q->rear = newNode;
}
}
// 出队列
int dequeue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return -1;
}
int data = q->rear->next->data;
Node* temp = q->rear->next;
if (q->rear == q->rear->next) {
q->rear = NULL;
}
else {
q->rear->next = temp->next;
}
free(temp);
return data;
}
int main() {
Queue q;
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
printf("%d\n", dequeue(&q));
printf("%d\n", dequeue(&q));
printf("%d\n", dequeue(&q));
printf("%d\n", dequeue(&q));
return 0;
}
```
阅读全文