zoukankan      html  css  js  c++  java
  • 用链表实现消息队列

    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 }
  • 相关阅读:
    Nested Lists比较经典的python代码
    Matching Character Ranges
    python 刷题记录
    SQL Access Advisor and SQL Tunning Advisor
    Reactor IO模型
    聊聊page cache与Kafka之间的事儿
    node.js cmd 输入npm-v无反应
    鼠标突然无反应,鼠标灯亮,鼠标灯不亮
    js图片转换为base64
    js实现倒计时60秒的简单代码
  • 原文地址:https://www.cnblogs.com/AndrewYin/p/9203611.html
Copyright © 2011-2022 走看看