数据结构之队列链式存储
//链式队列
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
typedef struct LinkNode{//链式队列节点
ElemType data;
struct LinkNode *next;
}LinkNode;
typedef struct{//链式队列
LinkNode *front_queue,*rear_queue;//队列得队头和队尾
}LinkQueue;
void initQueue(LinkQueue *head)
{
printf("初始化\n");
head->front_queue=head->rear_queue=(LinkNode *)malloc(sizeof(LinkNode));
head->front_queue->next=NULL;
}
//判断是否空队列 空返回一
int IsEmpty(LinkQueue head)
{
//printf("判断是否为空\n");
if(head.front_queue==head.rear_queue)
return 1;//空
return 0;
}
//尾插入队
void EnQueue(LinkQueue *tail,ElemType target)
{
//printf("入队\n");
LinkNode *newNode=(LinkNode *)malloc(sizeof(LinkNode));
newNode->data=target;
newNode->next=NULL;
tail->rear_queue->next=newNode;//先将队列连起来 队列尾部加一
tail->rear_queue=newNode;//现在队列最末端是新的节点了,所以再将队列尾指针更新
}
//出队,先进先出
void DeQueue(LinkQueue *front_Queue,ElemType *target)
{
LinkNode *head=front_Queue->front_queue;//不存数据的头节点
printf("出队\n");
//得判断是不是空队列
if(IsEmpty(*front_Queue))
{
printf("目前没有数据\n");
return;//是就退出
}
//常规 因为这个队列是有头节点的,所以取的数据是真正的节点的数据
*target=head->next->data;
//取完数据就是删除了,用真正的节点的下一个节点取代它就完成了
head->next=head->next->next;
//只有一个节点的情况
//如果只有一个节点,那么将next的next赋值给next后只有NULL,而我们在判空函数IsEmpty()的判定中写的是head.front_queue==head.rear_queue 是指针是否相当
//还有就是尾指针的安排,将最后一个节点删除了,那么尾指针也该指到头节点上了
if(front_Queue->rear_queue==head->next)
{
front_Queue->rear_queue=head;//让头尾指针又去指向头节点
}
}
void showQueue(LinkQueue head)
{
LinkNode *pMove=head.front_queue->next;//先进先看
printf("目前队列的元素:\n");
while(pMove)
{
printf("%d ",pMove->data);
pMove=pMove->next;
}
printf("\n");
}
int main()
{
int cot=5;
LinkQueue *head;
initQueue(head);
//得有个指针记录尾指针
LinkQueue *tail=head;
while(cot--)
{
EnQueue(tail,cot);
}
showQueue(*head);
ElemType a;
DeQueue(head,&a);
printf("取出的是%d\n",a);
showQueue(*head);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)