链表实现队列

举报
兔老大 发表于 2021/04/20 00:17:56 2021/04/20
【摘要】 这次写的还算正规,稍微压缩了一下代码,但是不影响阅读 画个图帮助理解: F->0->0->0<-R 第一个0不存数据    #include<stdio.h>#include<malloc.h>#include<stdlib.h>typedef int Elementype;//数据类型...

这次写的还算正规,稍微压缩了一下代码,但是不影响阅读

画个图帮助理解:

F->0->0->0<-R

第一个0不存数据 

 


  
  1. #include<stdio.h>
  2. #include<malloc.h>
  3. #include<stdlib.h>
  4. typedef int Elementype;//数据类型
  5. //节点结构
  6. typedef struct Node{
  7. Elementype Element;//数据域
  8. struct Node * Next;
  9. }NODE,*PNODE;
  10. // 定义队列结构体
  11. typedef struct QNode {
  12. PNODE Front;//队头
  13. PNODE Rear;//队尾
  14. } Queue, *PQueue;
  15. void init(PQueue queue)//初始化
  16. {//头尾指向同一内存空间//头结点,不存数据
  17. queue->Front = queue->Rear = (PNODE)malloc(sizeof(NODE));
  18. queue->Front->Next = NULL;//头结点指针为空
  19. }
  20. int isEmpty(PQueue queue)//判空·
  21. {
  22. if(queue->Front == queue->Rear)return 1;
  23. return 0;
  24. }
  25. void insert(PQueue queue,Elementype data)//入队
  26. {
  27. PNODE P = (PNODE)malloc(sizeof(NODE));//初始化
  28. P->Element = data;
  29. P->Next = NULL;
  30. queue->Rear->Next = P;//入队
  31. queue->Rear = P;
  32. }
  33. void delete(PQueue queue,int * val)//出队,用val返回值
  34. {
  35. if(isEmpty(queue))printf("队空");
  36. else
  37. {
  38. PNODE P = queue->Front->Next;//前一元素
  39. *val = P->Element;//记录值
  40. queue->Front->Next = P->Next;//出队
  41. //注意一定要加上判断,手动模拟一下就明白了
  42. if(P==queue->Rear)queue->Rear = queue->Front;
  43. free(P);//注意释放
  44. P = NULL;
  45. }
  46. }
  47. void destroy(PQueue queue)//释放
  48. {
  49. //从头开始删
  50. while(queue->Front != NULL)//起临时指针作用,无需再用别的空间
  51. {
  52. queue->Rear = queue->Front->Next;
  53. free(queue->Front);
  54. queue->Front = queue->Rear;
  55. }
  56. }
  57. //测试
  58. int main(void)
  59. {
  60. int i;
  61. int e;
  62. Queue a;
  63. PQueue queue=&a;
  64. init(queue);
  65. for(i=0;i<10;i++)
  66. insert(queue,i);
  67. while(!isEmpty(queue))//遍历
  68. {
  69. delete(queue,&e);
  70. printf("%d ",e);
  71. }
  72. if(isEmpty(queue))printf("1\n");
  73. delete(queue,&e);
  74. destroy(queue);
  75. }

 

文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。

原文链接:fantianzuo.blog.csdn.net/article/details/82863168

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。