昨天介紹了用array的方式做Queue,今天來介紹用linked list製作!
一、single linked list
宣告:
1.Node structure is:
data | link |
---|---|
2.rear,front:pointer = Null; |
{
New(t);
t➝Data=item;
t➝link=Null;
if(Front==Null) then Front=t; //Q空
else Rear➝link=t; //Q非空
Rear=t;
}
{
if(front==Null) then return "Q empty";
else{
①t = Front;
②item = Front➝Data;
③Front = Front➝link;
④free(t);
if(front==Null) then rear = Null;
return item;
}
}
二、circular linked list
只用一個pointer即可表示尾及前端
即rear:指向尾端
rear➝link:前端
宣告:
1.Node structure is:
data | link |
---|---|
2.Rear:pointer = Null; |
{
New(t);
t➝Data=item;
if(Rear==Null) then t➝link=t; //Q空
else{ //Q非空
t➝link=Rear➝link;
Rear➝link=t;
}
rear=t; //剛插入的t變成rear
}
{
if(Rear==Null) then return "Q empty";
①t = Rear➝link;
②item = (Rear➝link)➝Data;
③Rear➝link = (Rear➝link)➝link;
④free(t);
}