用c语言给出完整代码 算法设计:在一个循环链队中只有尾指针(记为 rear,结点结构为数据源data,指针域为next,没有头 结点),请给出这个队列的入队、出队实现过程并测 试。
时间: 2024-05-08 07:16:48 浏览: 80
数据结构算法-习题-答案-带头结点的循环链表表示队列,并且只设一个指针指向队尾元素结点注意不设头指针.docx
5星 · 资源好评率100%
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct Queue {
Node *rear;
} Queue;
void initQueue(Queue *queue) {
queue->rear = NULL;
}
void enQueue(Queue *queue, int data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
if (queue->rear == NULL) {
queue->rear = node;
node->next = node;
} else {
node->next = queue->rear->next;
queue->rear->next = node;
queue->rear = node;
}
}
int deQueue(Queue *queue) {
if (queue->rear == NULL) {
printf("Queue is empty.\n");
return -1;
}
int data;
if (queue->rear->next == queue->rear) {
data = queue->rear->data;
free(queue->rear);
queue->rear = NULL;
} else {
Node *node = queue->rear->next;
data = node->data;
queue->rear->next = node->next;
free(node);
}
return data;
}
int main() {
Queue queue;
initQueue(&queue);
enQueue(&queue, 1);
enQueue(&queue, 2);
enQueue(&queue, 3);
printf("%d\n", deQueue(&queue));
printf("%d\n", deQueue(&queue));
printf("%d\n", deQueue(&queue));
printf("%d\n", deQueue(&queue));
return 0;
}
```
阅读全文