用链表实现消息队列

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值