链式队列【数据结构】

张开发
2026/4/2 23:33:21 15 分钟阅读
链式队列【数据结构】
核心定义定义是一个插入删除功能受到限制的线性表队列受到的限制和栈不太一样栈式只能在一端进行插入和删除操作而队列是在一端进行插入另一端进行删除先进先出 FIRST IN FIRST OUT头文件定义队列节点结构typedefintELEMTYPE;//有效节点typedefstructLQNode{ELEMTYPE data;structLQNode*next;}LQNode;//辅助节点typedefstructLink_Queue{structLQNode*front;//队头指针structLQNode*rear;//队尾指针}Link_Queue;1.初始化voidInit_LQ(Link_Queue*plq);2.入队用尾插模拟boolPush_LQ(Link_Queue*plq,ELEMTYPE val);3.出队用头删模拟boolPop_LQ(Link_Queue*plq);4.获取队头元素值ELEMTYPEFront_LS(Link_Queue*plq);5.获取当前队列的有效元素个数intSize_LQ(Link_Queue*plq);6.判空boolEmpty_LQ(Link_Queue*plq);7.销毁voidDestroy(Link_Queue*plq);8.打印voidShow(Link_Queue*plq);源文件引用的头文件#defineCRT_NO_WARNINGS#includestdio.h#includeassert.h#includestdlib.h#includestring.h#includememory.h#includeLinked_Queue.h1.初始化voidInit_LQ(Link_Queue*plq){assert(plq!NULL);plq-frontNULL;plq-rearNULL;}2.入队用尾插模拟boolPush_LQ(Link_Queue*plq,ELEMTYPE val){assert(plq!NULL);LQNode*newnode(LQNode*)malloc(sizeof(LQNode));if(newnodeNULL)exit(EXIT_FAILURE);newnode-dataval;if(Empty_LQ(plq)){newnode-nextNULL;plq-frontplq-rearnewnode;returntrue;}newnode-nextplq-rear-next;plq-rear-nextnewnode;plq-rearnewnode;returntrue;}3.出队用头删模拟boolPop_LQ(Link_Queue*plq){assert(plq!NULL);if(Empty_LQ(plq))returnfalse;LQNode*qplq-front;if(plq-front-nextNULL){free(plq-front);plq-rearNULL;plq-frontNULL;returntrue;}plq-frontq-next;free(q);qNULL;returntrue;}4.获取队头元素值ELEMTYPEFront_LS(Link_Queue*plq){assert(plq!NULL);if(Empty_LQ(plq))exit(EXIT_FAILURE);returnplq-front-data;}5.获取当前队列的有效元素个数intSize_LQ(Link_Queue*plq){assert(plq!NULL);intcount0;for(LQNode*pplq-front;p!NULL;pp-next){count;}returncount;}6.判空boolEmpty_LQ(Link_Queue*plq){assert(plq!NULL);returnplq-frontNULL;}7.销毁voidDestroy(Link_Queue*plq){assert(plq!NULL);LQNode*pplq-front;LQNode*qNULL;while(p!NULL){qp-next;free(p);pq;}plq-frontplq-rearNULL;}8.打印voidShow(Link_Queue*plq){assert(plq!NULL);if(Empty_LQ(plq))return;for(LQNode*pplq-front;p!NULL;pp-next){printf(%d\n,p-data);}printf(\n);}测试函数intmain(){Link_Queue head;Init_LQ(head);Push_LQ(head,1);Push_LQ(head,2);Push_LQ(head,3);Show(head);Pop_LQ(head);Show(head);//int aim Front_LS(head);intaimSize_LQ(head);printf(%d\n,aim);Destroy(head);}

更多文章