|
佇列 (Queue) ppt 下載 (動態配置) 又稱為隊列(queue),電腦科學中的一種抽象資料型別,是先進先出(FIFO, First-In-First-Out)的線性表。 在具體應用中通常用連結串列或者陣列來實現。 佇列 有兩個操作方式。 1. 放資料處。 2. 指向下一個資料。 有兩個操作方式。 1.put() //將資料加入佇列。(有些工程師會寫 Add()) 2.get() //從佇列取出資料,需注意佇列是空的。(有些工程師會寫 Delete()) 傳統非物件寫法:
|
|||
| 物件寫法 |
struct node{
int data;
node *next;
};
class Queue{
private:
node *head;
public:
Queue(){
head=NULL;
}
void put(int x){//將資料 x 放入佇列
if(head==NULL){
head=new node();//向系統要一份節點
head->data=x;//把資料放到節點
head->next=NULL;//下一筆接地
}
else{
node *p;
p=head;
while(p->next!=NULL){//搜尋佇列到最後面,把資料加到最後面
p=p->next;
}
p->next=new node();//向系統要一份節點
p=p->next;//加入新的節點
p->data=x;//把資料放到節點
p->next=NULL;//下一筆接地
}
}
int get(){ //從佇列取出料傳回
if(head==NULL) { //空佇列
std::cout << "Queue empty\n";
return(-1);
}
else{
node *p=head;//暫時記住要取出的節點
int u;
head=head->next;//將開頭指向下一個節點
u=p->data;//取出節點內的資料
delete(p);//將節點歸還系統
return(u);
}
}
};
int main(int argc, char** argv) {
Queue t;
t.put(110);
t.put(34);
cout << t.get() << endl;
t.put(28);
cout << t.get() << endl;
cout << t.get() << endl;
cout << t.get() << endl;
t.put(79);
cout << t.get() << endl;
cout << t.get() << endl;
return 0;
}
|