链式队列

还是打算写一写吧

 

  1. #include<iostream>
  2. #include<malloc.h>
  3. #include<stdlib.h>
  4. using namespace std;
  5. #define OK 1
  6. #define ERROR 0
  7. #define OVERFLOW -2
  8. typedef int Status;
  9. typedef int QElemType; 
  10. typedef struct QNode
  11. {
  12.     QElemType data;
  13.     struct QNode *next;
  14.         }QNode,*QueuePtr;
  15. typedef struct
  16. {
  17.     QueuePtr front;
  18.     QueuePtr rear;
  19.         }LinkQueue;
  20. Status InitQueue(LinkQueue &Q)
  21. {
  22.       Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode));
  23.       if(!Q.front) exit(OVERFLOW);
  24.       Q.front->next=NULL;
  25.       return OK;
  26.       }
  27. Status EmptyQueue(LinkQueue &Q)
  28. {
  29.       return Q.front==Q.rear?true:false; }
  30.       
  31. Status EnQueue(LinkQueue &Q,QElemType e)
  32. {
  33.   QueuePtr p=(QueuePtr)malloc(sizeof(QNode));
  34.   if(!p) exit(OVERFLOW);
  35.   p->data=e;
  36.   p->next=NULL;
  37.   Q.rear->next=p;
  38.   Q.rear=p;
  39.   return OK;
  40.        }
  41. Status DeQueue(LinkQueue &Q,QElemType &e)
  42. {
  43.     if(EmptyQueue(Q)) return ERROR;
  44.     QueuePtr p=Q.front->next;
  45.     e=p->data;
  46.     Q.front->next=p->next;
  47.     if(Q.rear==p) Q.rear=Q.front;
  48.     free(p);
  49.     return OK;   }
  50. Status DestroyQueue(LinkQueue &Q)
  51. {
  52.        while(Q.front)
  53.        {Q.rear=Q.front->next;
  54.        free(Q.front);
  55.        Q.front=Q.rear;}
  56. return OK;
  57. }
  58. Status ClearQueue(LinkQueue &Q)
  59. {
  60.       Q.rear=Q.front;
  61.       Q.front->next=NULL;
  62.       return OK; }
  63. int QueueLength(LinkQueue Q)
  64. {
  65.    int n=0;
  66.    while(Q.front!=Q.rear)
  67.    {
  68.        n++;
  69.        Q.front==Q.front->next; }
  70.    return n;}
  71. Status GetHead(LinkQueue Q,QElemType &e)
  72. {
  73.     if(EmptyQueue(Q)) return ERROR;   
  74.     e=Q.front->next->data; 
  75.     return OK; }
  76. void visit(QueuePtr p)
  77. {
  78.      cout<<p->data<<endl;}
  79. Status QueueTraverse(LinkQueue Q,void visit(QueuePtr))
  80. {
  81.   if(EmptyQueue(Q)) return ERROR;
  82.   while(Q.front!=Q.rear)
  83.   {visit(Q.front->next); 
  84.   Q.front=Q.front->next;}
  85.   return OK;
  86. }
  87. int main()
  88. {
  89.     LinkQueue Q;
  90.     QElemType e;
  91.     InitQueue(Q);
  92.     for(int i=0;i<5;i++)
  93.     {cin>>e; 
  94.     EnQueue(Q,e);}
  95.     DeQueue(Q,e);
  96.     QueueTraverse(Q,visit);
  97.     DestroyQueue(Q);
  98.     return 0;
  99.     }
  100. 5 4 3 2 1
  101. 4
  102. 3
  103. 2
  104. 1
  105. 请按任意键继续. . .

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值