第十三章 数据结构基础--队列

本文深入探讨了队列的基本操作,包括入队、出队、队列长度计算及队列销毁过程。通过实例代码展示了如何使用结构体实现队列,并详细解释了每一步操作的实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.1 入队

入队:从队列的尾部加入结点。

#include <stdlib.h>

typedef struct student {
int age;
struct student *next;
}Stu;

typedef struct linkqueue {
Stu *front, *rear;
}queue;

queue *EnQueue(queue *head, int age) {
Stu *cur_stu;
cur_stu = (Stu *)malloc(sizeof(Stu));
cur_stu->age = age;
cur_stu->next = NULL;
if(head->rear == NULL) {
head->front = cur_stu;
head->rear = cur_stu;
} else {
head->rear->next = cur_stu;
head->rear = cur_stu;
}
return head;
}

1.2 出队

出队:从队列的头部删除结点。

queue *DeQueue(queue *head) {
Stu *cur_stu;
if(head->front == NULL) {
printf("had removed.\n");
} else {
cur_stu = head->front;
if (head->front == head->rear) {
head->front = NULL;
head->rear = NULL;
} else {
head->front = head->front->next;
}
free(cur_stu);
}
return head;
}

1.3 队列销毁

void DestroyQueue(queue *head) {
Stu *tmp_stu = NULL;

while (head->front) {
tmp_stu = head->front->next;
free(head->front);
head->front = tmp_stu;
}
}

1.4 队列长度

int LenQueue(queue *head) {
int i = 0;
Stu *cur_stu = head->front;


if (head->front == NULL) {
return i;
}
i++;

while (head->rear != cur_stu) {
i++;
cur_stu = cur_stu->next;
}
return i;
}


1.5 main函数调用

int main() {
queue *head_queue = NULL;
int age[5] = {1,2,3,4,5};
int len = 0;

head_queue = (queue *) malloc(sizeof(queue));
head_queue->front = head_queue->rear = NULL;

len = LenQueue(head_queue);
printf("length of queue: %d\n", len);


head_queue = EnQueue(head_queue, age[0]);
head_queue = EnQueue(head_queue, age[1]);
head_queue = EnQueue(head_queue, age[2]);
head_queue = EnQueue(head_queue, age[3]);
head_queue = EnQueue(head_queue, age[4]);

len = LenQueue(head_queue);
printf("length of queue: %d\n", len);

head_queue = DeQueue(head_queue);

len = LenQueue(head_queue);
printf("length of queue: %d\n", len);

DestroyQueue(head_queue);

return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值