假设以带头结点的单向循环链表表示队列,并且只设一个指针指向队尾 元素结点(注意:不设头指针),试设计并验证相应的队列初始化、队列判空、入队列、出队列和遍历队列算法。用c语言编写,要求能够自己输入数据
时间: 2024-05-15 21:17:41 浏览: 183
假定一个单向循环链表来表示队列(即循环链队),该队列只设一个队尾指针,不设队首指针,试编写下列各种运算的算法
4星 · 用户满意度95%
好的,我可以帮你解答这个问题。以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct {
Node *rear; // 队尾指针
} Queue;
// 初始化队列
void init(Queue *q) {
q->rear = NULL;
}
// 判断队列是否为空
int isEmpty(Queue *q) {
return q->rear == NULL;
}
// 入队列
void enqueue(Queue *q, int x) {
Node *p = (Node *)malloc(sizeof(Node));
p->data = x;
if (isEmpty(q)) { // 队列为空,插入第一个结点
q->rear = p;
p->next = p;
} else {
p->next = q->rear->next;
q->rear->next = p;
q->rear = p;
}
}
// 出队列
int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return -1;
}
int x = q->rear->next->data;
if (q->rear->next == q->rear) { // 队列中只有一个结点
free(q->rear);
q->rear = NULL;
} else {
Node *p = q->rear->next;
q->rear->next = p->next;
free(p);
}
return x;
}
// 遍历队列
void traverse(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return;
}
Node *p = q->rear->next;
do {
printf("%d ", p->data);
p = p->next;
} while (p != q->rear->next);
printf("\n");
}
int main() {
Queue q;
int x, choice;
init(&q);
do {
printf("\n1. Enqueue");
printf("\n2. Dequeue");
printf("\n3. Traverse");
printf("\n4. Quit");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the element to be inserted: ");
scanf("%d", &x);
enqueue(&q, x);
break;
case 2:
x = dequeue(&q);
if (x != -1) {
printf("The element deleted from queue is: %d\n", x);
}
break;
case 3:
traverse(&q);
break;
case 4:
exit(0);
default:
printf("Invalid choice!\n");
}
} while (choice != 4);
return 0;
}
```
这样就可以实现基于带头结点的单向循环链表的队列操作了。
阅读全文