隊列的數組實現,從隊尾進入,對頭刪除。
隊列長度用標志變量size,它是獨立於front和rear的一個變量。size == 0,隊列為空。size == capacity,滿隊列。
一、結點聲明
1 struct Node{ 2 int Capacity; 3 int Front; 4 int Rear; 5 int Size; 6 int *Array; 7 }; 8 typedef struct Node Queue;
Capacity隊列容量;Front,Rear為隊列首元素和尾元素的數組下標;Size為當前隊列大小;Array指向整形數組的指針,存放隊列元素。
二、非空判斷
1 int queue::isEmpty(Queue *Q) 2 { 3 return Q->Size == 0; //獨立於Q->Rear和Q->Front存在的一個標志 4 }
三、滿隊列判斷
1 int queue::isFull(Queue *Q) 2 { 3 return (Q->Size == Q->Capacity ); 4 }
四、創建隊列
1 queue::Queue *queue::createQueue(int maxElements) 2 { 3 cout << "Please input the value of maxElements: " << endl; 4 scanf_s("%d", &maxElements); 5 if (maxElements < minQueueSize) 6 { 7 cout << "The size of queue is too small!" << endl; 8 return 0; 9 } 10 else 11 { 12 Queue *Q; 13 Q = (Queue *)new(Queue); 14 if (Q == NULL) 15 cout << "Out of space!" << endl; 16 Q->Array = new int[maxElements]; 17 if (Q->Array == NULL) 18 cout << "Out of space!" << endl; 19 20 Q->Capacity = maxElements; 21 Q->Front = 1; 22 Q->Rear = 1; // Rear預初始化為1 23 Q->Size = 0; // 空隊列標志 24 makeEmpty(Q); 25 return Q; 26 } 27 }
五、清空隊列
1 void queue::makeEmpty(Queue *Q) 2 { 3 if (isEmpty(Q)) 4 cout << "Donnot need to makeEmpty the queue!" << endl; 5 Q->Size = 0; // 空隊列標志,初始狀態下標如下 6 Q->Front = 1; 7 Q->Rear = 0; 8 }
六、循環隊列實現
1 int queue::isCycle(int value, Queue *Q) 2 { 3 if (++value == Q->Capacity) //下標從0開始,故下標為Capacity,表示循環隊列的第一個元素,即下標為0 4 return 0; 5 return value; 下標小於Capacity,可正常自增 6 }
七、進隊列
1 queue::Queue *queue::enQueue(Queue *Q) 2 { 3 if (isFull(Q)) 4 cout << " Full queue! " << endl; 5 else 6 { 7 int x = 0; 8 cout << "Please input the number to enQueue!" << endl; 9 scanf_s("%d", &x); // 取地址符 10 Q->Size++; 11 Q->Rear = isCycle(Q->Rear,Q); // 循環隊列自增 12 Q->Array[Q->Rear] = x; 13 } 14 return Q; // 滿隊列則返回原隊列,未滿則進入隊列后返回該隊列 15 }
八、返回隊首元素
1 int queue::front(Queue *Q) 2 { 3 return Q->Array[Q->Front]; //只返回隊首元素,不出隊列 4 }
九、出隊列
1 queue::Queue *queue::deQueue(Queue *Q) 2 { 3 if (isEmpty(Q)) 4 cout << "Empty queue! " << endl; 5 else 6 { 7 cout << "The front element of queue is :" << Q->Array[Q->Front] << endl; 8 Q->Front++; 9 Q->Size--; 10 } 11 return Q; 12 }
十、處理隊列
1 void queue::disposeQueue(Queue *Q) 2 { 3 while (!isEmpty(Q)) 4 { 5 Q->Size = 0; //循環終止條件 6 free(Q->Array); 7 free(Q); 8 } 9 }