隊列是指具有一定操作約束的線性表
資料只能在一端進行插入,在另外一端執行刪除
先進先出 先來先服務
環狀隊列如何判斷隊列何時為空白 何時為滿?
如果 隊尾+1%MAXSIZE = 隊頭 則隊列為滿
如果 隊頭 == 隊尾 則隊列為空白
隊列的數組實現:
#include<iostream>#include<stdlib.h>#define MAXSIZE 6using namespace std;typedef int ElementType;//迴圈隊列實現struct QUEUE{int data[MAXSIZE];int head = 0; //頭指標int rear = 0; //尾指標};void push(QUEUE* q, ElementType element) {if ((q->head + 1) % MAXSIZE == q->rear) { //通過%MAXSIZE來判斷數組是空還是滿cout << "The Queue has been full!!" << endl;return;}q->data[q->head] = element; q->head = (q->head + 1) % MAXSIZE;}ElementType pop(QUEUE* q) {//判斷隊列是否為空白?if (q->head == q->rear) {cout << "The Queue is Empty!!" << endl;return 0;}q->data[q->rear] = NULL;q->rear = (q->rear + 1) % MAXSIZE;}int main() {QUEUE myQueue;push(&myQueue, 10);push(&myQueue, 20);push(&myQueue, 30);push(&myQueue, 40);push(&myQueue, 50);pop(&myQueue);pop(&myQueue);pop(&myQueue);pop(&myQueue);pop(&myQueue);system("PAUSE");return 0;}
隊列的迴圈鏈表實現:
#include<iostream>#include<stdlib.h>#define MAXSIZE 6using namespace std;typedef int ElementType;class NODE{friend class QUEUE;private:ElementType data; //資料域NODE* link; //指標域};class QUEUE {private:NODE* first;public:QUEUE() {first = new NODE();first->link = first; //前端節點指向自己}void show();void push(ElementType data);ElementType pop();};void QUEUE::push(ElementType data){NODE* newNode = new NODE();newNode->data = data;newNode->link = first->link;first->link = newNode;}ElementType QUEUE::pop() {NODE* temp;NODE* Ptr;Ptr = first->link;if (Ptr == first) {cout << "The Queue has been full!" << endl;return 0;}while (Ptr->link->link != first)Ptr = Ptr->link;int tempData = Ptr->link->data;temp = Ptr->link;Ptr->link = first;delete temp;return tempData;}void QUEUE::show() {NODE* Ptr;Ptr = first->link;while (Ptr != first) {cout << Ptr->data << endl;Ptr = Ptr->link;}}int main() {QUEUE myQueue;myQueue.push(10);myQueue.push(20);myQueue.push(30);myQueue.push(40);myQueue.show();cout << endl << endl;int a = myQueue.pop();int b = myQueue.pop();int c = myQueue.pop();cout << c << endl;myQueue.pop();system("PAUSE");return 0;}