資訊學奧賽系列課程:佇列及應用
阿新 • • 發佈:2018-12-30
佇列的概念:
現實生活中,經常可以看到佇列的例子,如排隊買票,先來的人買了票,先離開,後面來的只有等前面離開後,
才能買票離開,佇列就是類似排隊買票的一種資料結構。
佇列的定義:
佇列是限定在一端進行插入,另一端進行刪除特殊線性表。
允許出隊的一端稱為隊頭,允許入隊的一端稱為隊尾。
佇列的性質:
先進先出(FIFO),先進來的先出去,跟棧的區別,棧是先進後出。
佇列的操作:
入隊:在隊尾加入
出隊:在隊頭離開
佇列的表示:
在C++語言裡,一般用連結串列表示佇列,先定義每個結點的結構體,定義兩個指標head,tail分別指向
佇列的頭和尾,入隊和出隊的操作,通過改變指標來進行。具體程式碼如下:
#include <iostream> using namespace std; struct Node { int data; //佇列元素,可以是其他型別 Node* next; //指向下一個元素的指標 }; Node* head; //隊首指標 Node* tail; //隊尾指標 void initQueue(); //初始化佇列 void addItem(int x);//入隊 int outItem();//出隊 int main() { initQueue(); addItem(11); addItem(12); addItem(13); cout<<outItem()<<endl; cout<<outItem()<<endl; cout<<outItem()<<endl; cout<<outItem()<<endl; cout<<outItem()<<endl; cout<<outItem()<<endl; cout<<outItem()<<endl; return 0; } void initQueue() //初始化時,首尾指標指向相同的位置 { Node *temp = new Node; head =temp; tail =temp; tail->next =NULL; } void addItem(int x) //入隊時,改變尾指標指向 { Node *temp = new Node; temp->data =x; temp->next =NULL; tail->next =temp; tail = temp; } int outItem() //出隊,先判斷佇列是否為空 { if (head == tail) { cout<<"佇列已空"<<endl; return 0; } Node *temp = new Node; temp = head->next; int x=temp->data; head =head->next; return x; }
佇列相關的題目:
已知佇列(13,2,11,34,77,5,7,18,26,15)第一個進入佇列的元素是13,則第五個出佇列的元素是()
A.5 B.41 C.77 D.13 E.18