一、分析
隊列是一種先進先出的線性表,它只允許在表的一端進行插入,而在另一端刪除元素。允許插入的一端稱為隊尾,允許刪除的一端稱為隊頭。
循環隊列是一種以順序存儲結構表示的隊列,為了解決“假溢出”問題而將它設計成頭尾相接的循環結構,它的基本操作如下:
1、初始化循環隊列
2、銷毀循環隊列
3、清空循環隊列
4、檢測循環隊列是否為空
5、返回循環隊列的元素個數
6、返回循環隊列頭元素
7、向隊尾插入元素
8、刪除並返回隊頭元素
9、遍歷循環隊列
在循環隊列中,除了用一組地址連續的存儲單元依次存儲從隊頭到隊尾的元素外,還需要附設兩個整型變量front和rear分別指示隊頭和隊尾的位置。
在Java中,我們可以將循環隊列視作一個類,通過成員變量數組來表示一組地址連續的存儲單元,再定義兩個成員變量front和rear,將循環隊列的基本操作定義成類的方法,循環效果則用“模”運算實現,以此來實現循環隊列。這樣,初始化循環隊列就是將類實例化,銷毀就是銷毀實例化出來的對象。
二、實現
1、定義類屬性和構造函數
1 class InitQueue{ 2 3 private int [] queue = null; 4 5 private int front = 0; 6 7 private int rear = 0; 8 9 private boolean empty = true; //true表示循環隊列為空 10 11 public InitQueue(int max) { //構造指定大小的循環隊列 12 this.queue = new int[max]; 13 } 14 }
2、清空循環隊列
1 public void clearQueue() { 2 this.front = 0; 3 this.rear = 0; 4 this.empty = true; 5 }
3、檢測循環隊列是否為空
1 public boolean queueEmpty() { 2 if(this.empty == true) { 3 return true; 4 }else { 5 return false; 6 } 7 }
4、返回循環隊列的元素個數
1 public int queueLength() { 2 if (this.front == this.rear && this.empty == false) { 3 return this.queue.length; //如果循環隊列已滿,返回數組長度即元素個數 4 } 5 return (this.rear - this.front + this.queue.length) % this.queue.length; //否則,取模運算得到長度 6 }
5、返回循環隊列頭元素
1 public int [] getHead() { 2 3 if (this.empty == true) { 4 return null; 5 } 6 7 int [] i = new int[1]; 8 i[0] = queue[this.front]; 9 return i; 10 }
6、向隊尾插入元素
1 public boolean enQueue(int value) { 2 3 if (this.empty == false && this.front == this.rear) { 4 return false; 5 } 6 7 this.queue[this.rear] = value; 8 this.rear = (this.rear + 1) % this.queue.length; 9 this.empty = false; 10 return true; 11 }
7、刪除並返回隊頭元素
1 public int [] deQueue() { 2 3 if (this.empty == true) { 4 return null; 5 } 6 7 int [] i = new int[1]; 8 i[0] = this.queue[this.front]; //獲取隊頭元素 9 10 this.front = (this.front + 1) % this.queue.length; //刪除隊頭元素(front指針加一) 11 12 if(this.front == this.rear) { //如果循環隊列變空,改變標志位 13 this.empty = true; 14 } 15 return i; 16 }
8、遍歷循環隊列
1 public String queueTraverse() { //此處用輸出循環隊列表示遍歷 2 3 String s = ""; 4 int i = this.front; //i指向第一個元素 5 6 if(this.front == this.rear && this.empty == false) { //如果循環隊列已滿,取出第一個元素,i指向下一個元素 7 s += this.queue[i] + "、"; 8 i = (i + 1) % this.queue.length; 9 } 10 11 while (i != this.rear) { //如果未到末尾,則循環讀取元素 12 s += this.queue[i] + "、"; 13 i = (i + 1) % this.queue.length; 14 } 15 16 if(s.length() == 0) { //如果沒有讀取到元素,直接返回空字符串 17 return s; 18 } 19 return s.substring(0,s.length() - 1); //除去最后的頓號返回 20 }
三、小結
以上就是循環隊列用Java的實現,由於只定義了整數的數組,因此只能操作整數數據,但循環隊列的基本思想都已實現。