01.#include "stdafx.h"
02.#include <iostream>
03.//隊列
04.using namespace std;
05.typedef struct node{
06. node *next;//指向鏈表下一個節點
07.int data;
08.}node;
09.
10.//node表示隊列中的每個節點元素,queue表示隊列
11.typedef struct queue {
12.node *front;//隊首
13.node *rear;//隊尾
14.}queue;
15.
16.//創建空隊列
17.queue *CreateQueue(){
18. queue *q=new queue;
19. q->front=NULL;//把隊首指針置空
20. q->rear=NULL;//把隊尾指針置空
21. return q;
22.}
23.//入隊,從隊尾一端插入節點
24.queue *EnQueue(queue *q,int data){
25. if (q==NULL){//如果指針爲NULL,返回NULL
26. return NULL;
27. }
28. node *pnode=new node;
29. pnode->data=data;
30. pnode->next=NULL;
31. if (q->rear==NULL){//如果隊列爲空,則新節點即是隊首又是隊尾
32. q->rear=q->front=pnode;
33. }else{ //如果隊列不爲空,新節點放在隊尾,隊尾指針指向新節點
34. q->rear->next=pnode; //末尾節點的指針指向新節點
35. q->rear=pnode; //末尾指針指向新節點
36. }
37. return q;
38.}
39.//出隊,從隊頭一端刪除節點
40.queue *QuQueue(queue *q){
41. node *pnode=NULL;
42. pnode=q->front; //指向隊頭
43. if (pnode==NULL){ //如果隊列爲空,則返回NULL
44. cout<<"Empty queue!\n";
45. return NULL;
46. }
47. q->front=q->front->next; //把頭節點的下一個節點作爲頭節點
48. if (q->front==NULL){ //若刪除後隊列爲空,需對rear置空
49. q->rear=NULL;
50. }
51. delete pnode; //釋放內存
52. return q;
53.}
54.//隊列的測長
55.int GetLength(queue *q){
56. if (q==NULL || q->rear==NULL){
57. return 0;
58. }
59. int i=1;
60. node *pnode=q->front;
61. while (pnode->next!=NULL){
62. pnode=pnode->next;
63. i++;
64. }
65. return i;
66.}
67.//隊列的打印
68.void Print(queue *q){
69. node *pnode=q->front;
70. if (pnode==NULL){//如果隊列爲空,直接返回
71. cout<<"Empty queue!\n";
72. return;
73. }
74. while (pnode!=NULL){
75. cout<<pnode->data<<" ";
76. pnode=pnode->next;
77. }
78. cout<<endl;
79.}
80.int _tmain(int argc, _TCHAR* argv[])
81.{
82. queue *pA=NULL;
83. pA=CreateQueue();
84. pA=EnQueue(pA,2);
85. pA=EnQueue(pA,3);
86. pA=EnQueue(pA,4);
87. pA=EnQueue(pA,5);
88. Print(pA);
89. cout<<"The Length:"<<GetLength(pA)<<endl;
90. pA=QuQueue(pA);
91. pA=QuQueue(pA);
92. Print(pA);
93. cout<<"The Length:"<<GetLength(pA)<<endl;
94. system("pause");
95. delete [] pA;
96. return 0;
97.}
隊列的入隊,出隊,測長,打印操作 .
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.