c语言编写一个代码,在一个循环链队中只有尾指针(记为rear,结点结构为数据源data,指针域为next,没有管理头结点),请给出这个队列的入队、出队实现过程。
时间: 2024-05-07 13:16:06 浏览: 91
队列的结构体定义:
```
typedef struct node {
int data;
struct node *next;
} Node;
typedef struct queue {
Node *rear;
} Queue;
```
入队操作:
```
void enqueue(Queue *q, int data) {
Node *new_node = (Node *) malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
if (q->rear == NULL) {
q->rear = new_node;
q->rear->next = q->rear;
} else {
new_node->next = q->rear->next;
q->rear->next = new_node;
q->rear = new_node;
}
}
```
出队操作:
```
int dequeue(Queue *q) {
if (q->rear == NULL) {
printf("Queue is empty.\n");
return -1;
} else if (q->rear == q->rear->next) {
int data = q->rear->data;
free(q->rear);
q->rear = NULL;
return data;
} else {
Node *front = q->rear->next;
int data = front->data;
q->rear->next = front->next;
free(front);
return data;
}
}
```
阅读全文