博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用链表实现消息队列
阅读量:4514 次
发布时间:2019-06-08

本文共 1816 字,大约阅读时间需要 6 分钟。

l链表可以实现多种数据结构,消息队列,环形缓存等。下面先介绍消息队列的实现,后面介绍ring buf的实现。

 

1 /*FIFO队列中参数的类型*/ 2 typedef int QElemtype; 3  4  /*对节点的结构定义*/ 5 typedef struct QNode 6 { 7     QElemtype data; 8     struct QNode *next; 9 }QNode,*QueuePtr; 10 11 /*FIFO队列的结构定义*/ 12 typedef struct{ 13  QueuePtr head; 14  QueuePtr rear; 15 }LinkQueue; 16 LinkQueue updateListMsgQ; 17 18 /*.BH----------------------------------------------------------------- 19 ** 20 **函数名: 21 ** 22 **功能:链表实现消息队列,支持任意类型数据 23 ** 24 **参数: 25 ** 26 **返回值: 27 ** 28 **设计注记: 29 ** 30 **.EH----------------------------------------------------------------- 31 */ 32 //初始化队列 33 int Queue_Init(LinkQueue* que) 34 { 35 que->head=que->rear=(QueuePtr)malloc(sizeof(QNode)); 36 if(!que->head) //这段代码对队列里面的用户自定义数据类型进行了初始化 37 return ERROR; 38 return OK; 39 } 40 41 //回收队列 42 int Queue_Destory(LinkQueue* que) 43 { 44 while(que->head) 45  { 46 que->rear = que->head->next; 47 free(que->head); 48 que->head=que->rear; 49  } 50 return OK; 51 } 52 53 /*将元素插到尾部*/ 54 int Queue_Push(LinkQueue* que,QElemtype e) 55 { 56 QueuePtr p = (QueuePtr)malloc(sizeof(QNode)); 57 if(!p) //若未能申请到空间,便退出 58 return ERROR; 59 p->data=e; 60 p->next=NULL; 61 62 que->rear->next = p; 63 que->rear=p; 64 return OK; 65 } 66 67 /*指针que指向头节点的后一节点,既要出队的节点*/ 68 int Queue_Pop(LinkQueue* que,QElemtype *t) 69 { 70 if(que->rear==que->head) 71 return ERROR; //队列为空 72 73 QueuePtr p = que->head->next; 74 *t=p->data; 75 76 que->head->next=p->next; 77 if(que->rear==p) //这个判断是 确保在清空队列的时候,让rear指针归位。 78 que->rear=que->head; 79 free(p); 80 return OK; 81 } 82 83 /*遍历队列*/ 84 int Queue_View(LinkQueue* que) 85 { 86 if(que->rear == que->head) 87 return ERROR; 88 89 QueuePtr p =que->head->next; 90 while(p) 91  { 92 printf("val:%d",p->data); 93 p=p->next; 94  } 95 return OK; 96 }

 

转载于:https://www.cnblogs.com/AndrewYin/p/9203611.html

你可能感兴趣的文章
NOIp2016纪录[那些我所追求的]
查看>>
(VB)定时更换(IE)代理IP(代理轮换)
查看>>
Node.js HTTP Server对象及GET、POST请求
查看>>
LintCode Coins in a Line
查看>>
[题解]POJ 3207 Ikki's Story IV - Panda's Trick
查看>>
Translate Animation
查看>>
MyEclipse使用反向工程
查看>>
获取当前页面url信息
查看>>
Java容器类源码分析前言之集合框架结构(基于JDK8)
查看>>
linux下C/C++程序的内存布局
查看>>
单词计数问题
查看>>
php 魔术方法 __autoload()
查看>>
js div拖动动画运行轨迹效果
查看>>
使用Struts 2框架实现文件下载
查看>>
把工程部署在tomcat的root路径下
查看>>
topcoder SRM 625 DIV2 AddMultiply
查看>>
Leetcode Climbing Stairs
查看>>
腾讯2013实习笔试题
查看>>
Recipe 1.9. Processing a String One Word at a Time
查看>>
Linux 下查看系统是32位 还是64 位的方法
查看>>