摘要:本文主要向大家介绍了C++语言之链表初解关于队列的入队和出队,通过具体的代码向大家展示,希望对大家学习C++语言有所帮助。
本文主要向大家介绍了C++语言之链表初解关于队列的入队和出队,通过具体的代码向大家展示,希望对大家学习C++语言有所帮助。
自己复习了一下简单队列的基本操作,其中要注意的是队头和队尾要始终保持位置正确~还是老习惯,上代码+注释啦~
Code:
[cpp] view plain copy 1. #include<iostream> 2. using namespace std; 3. 4. typedef struct node 5. { 6. int data; 7. struct node *next; 8. }node;//定义指针结构 9. 10. typedef struct queue 11. { 12. node *first, *rear;//定义队头、队尾指针。 13. }queue; 14. //入队 15. queue *insert(queue *Q, int x) 16. { 17. node *i; 18. //先创建要入队的节点。 19. i = (node *)malloc(sizeof(node)); 20. i->data = x; 21. if(Q == NULL) 22. {//如果队列结构体为空(还未插入值),则创建队列结构体。 23. Q = (queue *)malloc(sizeof(queue)); 24. Q->first = Q->rear = i; 25. Q->rear->next = NULL; 26. } 27. else 28. {//按顺序将节点入队。 29. Q->rear->next = i; 30. Q->rear = i; 31. i->next = NULL; 32. } 33. return Q; 34. } 35. //出队 36. queue *del(queue *Q) 37. { 38. node *temp; //先定义一个中间节点,以便将队头处理完后将原队头空间释放。 39. if(Q->first == NULL) 40. {//如果队列唯空,则报错退出。 41. printf("Queue is null !"); 42. return NULL; 43. } 44. else 45. {//和单链表删除头节点的处理一样 46. temp = Q->first; 47. Q->first = Q->first->next; 48. free(temp);//别忘了释放哦~ 49. } 50. return Q; 51. } 52. //打印队列 53. void print(queue *Q) 54. {//与单链表的处理一样 55. node *temp; 56. temp = Q->first; 57. printf("Output the Queue : "); 58. while(1) 59. { 60. if(temp == NULL) break; 61. if(temp != Q->rear) printf("%d<-", temp->data); 62. else printf("%d\n", temp->data); 63. temp = temp->next; 64. } 65. } 66. int main() 67. { 68. queue *Q = NULL; 69. int x; 70. printf("Insert Queue (end with 0) : "); 71. //插入队列 72. while(scanf("%d", &x) != EOF && x != 0) 73. { 74. Q = insert(Q, x); 75. } 76. print(Q); 77. //出队 78. printf("\nAfter deleting~\n"); 79. Q = del(Q); 80. print(Q); 81. printf("\n"); 82. return 0; 83. }
运行示例:
本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号