Java实现循环队列
数组实现
public class Queue_<T> {
// 循环队列的数组
private Object[] object;
// 首指针
private int front;
// 尾指针
private int rear;
public Queue_() {
object = new Object[20];
front = rear = 0;
}
// 从尾部向队列添加元素
public void enQueue(int value) {
if (isFull()) {
throw new OutOfMemoryError();
} else {
object[rear] = value;
rear = (rear + 1) % 20;
}
}
// 从首部删除队列元素
public void deQueue() {
if (isEmpty()) {
throw new NullPointerException();
} else {
front = (front + 1) % 20;
}
}
// 返回队首元素
public T Front() {
if (isEmpty()) return null;
else
return (T) object[front];
}
// 返回队尾元素
public T Rear() {
if (isEmpty()) return null;
else
return (T) object[(rear - 1 + 20) % 20];
}
// 判断队列是否为空
public boolean isEmpty() {
return (rear == front);
}
// 判断队列是否已满
public boolean isFull() {
return (rear + 1) % 20 == front;
}
// 返回队列长度
public int size() {
return (rear - front + 20) % 20;
}
}
Java实现链式对联
内部类实现
public class Queue_plus<T> {
// 节点
private class queue<T> {
Object object;
queue next;
}
// 首指针
queue<T> front;
// 尾指针
queue<T> rear;
int size;
public Queue_plus() {
front = rear = null;
}
// 从队列尾部添加元素
public void enQueue(T t) {
if (t == null) {
throw new NullPointerException();
}
if (front == null) {
front = rear = new queue<T>();
front.object = t;
front.next = null;
} else {
rear.next = new queue<T>();
rear = rear.next;
rear.object = t;
rear.next = null;
}
}
// 从队列首部删除元素
public void deQueue() {
if (!isEmpty())
front = front.next;
else throw new NullPointerException();
}
// 返回队首元素
public T Front() {
return (T) front.object;
}
// 返回队尾元素
public T Rear() {
return (T) rear.object;
}
// 判断队列是否为空
public boolean isEmpty() {
if (front == null) {
return true;
} else return false;
}
// 返回队列长度
public int size() {
return size;
}
}
不足之处望指正。