數組模擬隊列的簡單實現方式代碼如下:
public class ArrayQueue {
private int maxSize;
private int front;
private int tail;
private int[] array;
public ArrayQueue(int queueSize) {
maxSize = queueSize;//最大元素個數
array = new int[queueSize];
front = -1;//頭結點
tail = -1;//尾結點
}
private boolean isEmpty() {
return front == tail;
}
private boolean isFull() {
return maxSize == front + 1;
}
//添加元素
public void addQueue(int i) {
if (isFull()) {
throw new RuntimeException("隊列已滿");
}
tail++;
array[tail] = i;
}
//獲取元素
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("隊列爲空");
}
front++;
return array[front];
}
public void showQueue() {
if (isEmpty()) {
throw new RuntimeException("隊列爲空");
}
for (int i = 0; i <maxSize ; i++) {
System.out.printf("隊列第 %d 個元素爲: %d ", i, array[i]);
}
}
}
存在問題,加入隊列在數組下標爲1的地方添加了元素,當這個元素出隊列後,這個數組的位置不能重複使用,會有空間浪費的問題
解決方式,環形隊列實現
public class CircleQueue {
private int maxSize;//最大元素個數
private int front;//首節點位置
private int tail;//尾結點位置的前一個位置
private int[] array;
public CircleQueue(int queueSize) {
maxSize = queueSize;
array = new int[queueSize];
}
private boolean isEmpty() {
return front == tail;
}
/**
* 判斷隊列是否已滿
* 例如:最大元素爲4,因爲tail指向尾結點前一個位置,棧中最多能存3個元素,
* 如果tail=3,front=0,此時棧中元素已滿。滿足(tail + 1) % maxSize == front
*/
private boolean isFull() {
return (tail + 1) % maxSize == front;
}
//添加元素
public void addQueue(int i) {
if (isFull()) {
throw new RuntimeException("隊列已滿");
}
array[tail] = i;
//加入tail爲3,0的位置是空的,則(3+1)%4 = 0,剛好tail的值置爲0,
tail = (tail + 1) % maxSize;
}
//獲取元素
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("隊列爲空");
}
//這裏front是指向隊列的第一個元素
//先將front對應的值保存到一個臨時變量
//將front後移,考慮取模形成一個環
//返回臨時變量
int value = array[front];
front = (front + 1) % maxSize;
return value;
}
public void showQueue() {
if (isEmpty()) {
throw new RuntimeException("隊列爲空");
}
for (int i = front; i < front + size(); i++) {
System.out.printf("array[%d]=%d\n", i % maxSize, array[i % maxSize]);
}
}
//返回隊列的有效元素個數
public int size() {
return (tail + maxSize - front) % maxSize;
}
}