//隊列(循環隊列),只能在一端進行插入,另一端進行刪除的操作受限的線性表
//屬性:隊列長度len, 數據(數組),頭指針和尾指針,頭指針刪除,尾指針添加
//方法:初始化,入隊,出隊
//普通隊列存在假溢出問題(尾指針到達隊尾,無法繼續添加元素,但隊列中卻仍有空位),爲此可將隊列看成一個環
//尾指針和頭指針都從0開始,尾指針到MAX-1後,若再添加元素,尾指針置0
//關鍵點:1,Q.tail=(Q.tail+1)%MAX,即尾指針到MAX-1時,置0;2,(this.tail+1)%this.MAX==this.head頭尾指針相遇,隊列滿
//隊列中元素個數(tail-head+MAX)
class TestQueue{
private int len;//記錄隊列元素個數
private int[] data;//元素
private int head;//頭指針
private int tail;//尾指針
int MAX;
/*隊列初始化,隊列容量,頭尾指針*/
void InitQueue(int max){
this.len=0;this.head=0;this.tail=0;//從0開始,循環隊列
this.MAX=max;//隊列容量
this.data=new int[MAX];
}
/*入隊,尾指針,判斷是否到達隊尾*/
boolean EnQueue(int data){
if ((this.tail+1)%this.MAX==this.head) return false;//頭尾指針相遇,隊列滿
else {
this.tail=(this.tail+1)%this.MAX;//移動尾指針
this.data[this.tail]=data;//保存數據
this.len++;;
return true;
}
}
/*出隊,*/
int DeQueue(){
if (this.len==0) return 0;
else {
this.head=(this.head+1)%this.MAX; //頭指針後移一位(當前的直接取出了,指針還沒移動),指向下一個待出隊元素。head=MAX-1時,第0個元素出列,
this.len--;//隊列長度-1
return this.data[this.head];
}
}
public static void main(String[] args){
TestQueue q=new TestQueue();
q.InitQueue(10);
for (int i=0; i<10; i++) {
q.EnQueue(i);
}
for (int i=0; i<10; i++) {
System.out.println( q.DeQueue() );
}
}
}
隊列
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.