假设以带头结点的循环链表表示队列,并且只设一个指针指向队尾元素结点,试编写相应的置空队、判队空、入队和出队算法’、‘
时间: 2024-01-14 21:02:54 浏览: 53
好的,我可以回答这个问题。以下是相应的代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Queue {
struct Node *rear;
};
//创建空队列
void createQueue(struct Queue *q) {
q->rear = NULL;
}
//判断队列是否为空
int isQueueEmpty(struct Queue *q) {
return (q->rear == NULL);
}
//入队列
void enqueue(struct Queue *q, int data) {
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
if (q->rear == NULL) {
q->rear = temp;
q->rear->next = q->rear;
} else {
temp->next = q->rear->next;
q->rear->next = temp;
q->rear = temp;
}
}
//出队列
int dequeue(struct Queue *q) {
if (isQueueEmpty(q)) {
printf("队列为空!");
return 0;
}
int data;
if (q->rear->next == q->rear) {
data = q->rear->data;
free(q->rear);
q->rear = NULL;
} else {
struct Node *temp = q->rear->next;
data = temp->data;
q->rear->next = q->rear->next->next;
free(temp);
}
return data;
}
int main() {
struct Queue q;
createQueue(&q);
if (isQueueEmpty(&q)) {
printf("队列为空!\n");
}
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
printf("队列出队的顺序是:%d %d %d\n", dequeue(&q), dequeue(&q), dequeue(&q));
return 0;
}
```
希望能回答您的问题!下一个问题是?
阅读全文