class LinkedQueue<T> {
/**
* 队列大小,由构造函数初始化
*/
private int maxSize;
/**
* 队头
*/
private Node front = null;
/**
* 队尾
*/
private Node rear = null;
/**
* 队列实际元素个数
*/
private int nItems;
/**
* 初始化队列,并指定队列长度
*
* @param maxSize
*/
public LinkedQueue(int maxSize) {
this.maxSize = maxSize;
front = null;
rear = null;
this.nItems = 0;
}
/**
* 讲一个数据放入队列
*
* @param data
*/
public void enqueue(T data) {
Node node = new Node(data);
if (isEmpty()) {
front = node;
front.next = null;
rear = node;
rear.pre = null;
nItems++;
return;
}
if (size() == 1) {
rear = node;
front.next = rear;
rear.pre = front;
nItems++;
return;
}
if (isFull()) {
System.out.print("超过队列已满,无法入队");
return;
}
node.pre = rear;
rear.next = node;
rear = node;
nItems++;
}
/**
* 将数据出队
*
* @return
*/
public T dequeue() {
Node temp = null;
if (isEmpty()) {
System.out.println("队列已空,无法出队");
return null;
}
if (size() == 1) {
temp = front;
front = null;
rear = null;
nItems--;
return temp.data;
}
if (size() == 2) {
temp = front;
front = rear;
front.next = null;
rear.pre = null;
nItems--;
return temp.data;
}
temp = front;
front = front.next;
nItems--;
return temp.data;
}
/**
* 判断队列是否为空
*
* @return
*/
public boolean isEmpty() {
return nItems == 0;
}
/**
* 判断队列是否已满
*
* @return
*/
public boolean isFull() {
return nItems == maxSize;
}
/**
* 获取队列的实际数据个数
*
* @return
*/
public int size() {
return nItems;
}
/**
* 将数据封装成节点
*
* @author John
*
*/
private class Node {
T data;
Node next;
Node pre;
public Node(T data) {
this.data = data;
}
}
}