本文共计547个文字,预计阅读时间需要3分钟。

javapackage com.hongliang;
/** * 队列(Queue)的实现,作为先进先出(FIFO)的线性结构, * 支持在队首获取元素,在队尾插入元素。 */public class Queue { // 队列的实现细节...}
队列(Queue)作为一个先进先出(FIFO) 的线性结构,支持在队首获取元素,在对尾插入元素。
package com.hongliang;
/**
* 队列顺序存储方式的实现
* @author KevinHong
*/
public class Queue
{
private Object[] data = null; //存储队列的数据元素的数组
private int front = 0; //列头元素的下标
private int rear = 0; //列尾元素的下标
private int count = 0; //队列的个数
private int capacity = 0; //队列初始化的大小
public Queue() {
this(10);
}
/**
* 初始化队列,声明队列的长度
* @param initialSize 队列初始化的长度
*/
public Queue(int initialSize) {
if(initialSize >= 0) {
data = new Object[initialSize];
this.capacity = initialSize;
this.count = 0;
this.front = 0;
this.rear = 0;
} else {
throw new RuntimeException("非法的初始化值,初始化值不能小于0");
}
}
/**
* 判断该队列是不是空队列
* @return 返回是否是空队列
*/
public boolean isEmpty() {
return front == rear && count == 0;
}
/**
* 判断该队列是不是已满
* @return 返回队列是否已满
*/
public boolean isFull() {
return front == rear && count == capacity;
}
/**
* 队列进行入列操作
* @param element 添加到队列中的数据元素
* @return 返回操作是否成功
*/
public boolean append(E element) {
if(isFull()) {
throw new RuntimeException("队列已经满,不能被插入");
}
data[rear] = element;
count++;
if(rear + 1 == capacity) {
rear = 0;
} else {
rear++;
}
return true;
}
/**
* 队列进行出列操作
* @return 返回队列中出列的数据元素
*/
public E poll() {
if(isEmpty()) {
throw new RuntimeException("队列是空的,不能取出数据");
}
E element = (E)data[front];
data[front] = null;
if(front + 1 == capacity) {
front = 0;
} else {
front++;
}
count--;
return element;
}
/**
* 获取队头数据元素
* @return 返回队头数据元素
*/
public E peak() {
if(isEmpty()) {
throw new RuntimeException("队列是空的,不能获得数据");
}
E element = (E)data[front];
return element;
}
/**
* 获取队列的长度
* @return 返回队列的长度
*/
public int size() {
return count;
}
/**
* 将顺序表转换成字符串
* @return 转换后的字符串
*/
@Override
public String toString() {
String toString = "[";
for(int i = 0; i < size(); i++) {
if(i != size() - 1) {
toString += data[i] + "," ;
} else {
toString += data[i] + "";
}
}
toString += "]";
return toString;
}
}
