?? arrayqueue.java
字號:
package org.huhuiyu.datastructures;
public class ArrayQueue {
private int count;
private int front; // 前端索引
private int back; // 尾端索引
private Object[] datas; // 隊列數據
public ArrayQueue(int size) {
datas = new Object[size];
clear();
}
/**
* 加入數據到隊列
*
* @param data
* 加入到隊列的數據
*/
public void enqueue(Object data) {
if (count == datas.length) {
throw new IllegalStateException("隊列已滿!");
}
back = (back + 1) % datas.length; // 計算隊列末端索引
datas[back] = data; // 加入到隊列末端
count++;
}
/**
* 出隊并返回出隊的數據
*
* @return 出隊的數據
*/
public Object dequeue() {
if (isEmpty()) {
throw new IllegalStateException("隊列是空的!");
}
front = (front + 1) % datas.length; // 計算隊列前端索引
Object data = datas[front]; // 獲取隊列前端數據
datas[front] = null; // 置空數組數據
count--;
return data;
}
/**
* 查看排在隊列最前端的數據
*
* @return 排在隊列最前端的數據
*/
public Object peek() {
if (isEmpty()) {
throw new IllegalStateException("隊列是空的!");
}
return datas[front];
}
public void clear() {
front = 0;
back = 0;
count = 0;
}
public boolean isEmpty() {
return count == 0;
}
public int size() {
return count;
}
public static void main(String[] args) {
int length = 10;
ArrayQueue queue = new ArrayQueue(length);
for (int i = 0; i < length; i++) {
queue.enqueue(i);
}
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
queue.enqueue(10);
System.out.println(queue.peek());
while (!queue.isEmpty()) {
System.out.println(queue.dequeue());
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -