資料結構 隊列的實現

來源:互聯網
上載者:User

隊列是指具有一定操作約束的線性表

資料只能在一端進行插入,在另外一端執行刪除

先進先出 先來先服務


環狀隊列如何判斷隊列何時為空白 何時為滿?

如果 隊尾+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;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.