一、代码如下
public class LinkQueue<T>{
private Node<T> front,rear;
private int length;
//构造一个空的队列
public LinkQueue() {
length = 0;
front = rear = new Node<>(null);
}
//在队列的队尾插入一个新元素
public void EnQueue(T obj) {
rear = rear.next = new Node<T>(obj,null);
length++;
}
//删除队列队头元素
public T DeQueue( ) {
if (isEmpty()){
System.out.println("链队列为空,无法执行删除操作");
return null;
}
Node<T> p = front.next;
T x = p.data;
front.next = p.next;
length--;
if (front.next == null){
rear = front;
}
return x;
}
//取队列队头元素
public T getHead( ){
if (isEmpty()){
System.out.println("链队列为空,无法取对头元素");
return null;
}
return front.next.data;
}
//求出队列中数据元素的个数
public int size( ){
return length;
}
//判断当前队列是否为空
public boolean isEmpty(){
return length == 0;
}
//依次访问队列中每个元素并输出
public void nextOrder(){
Node<T> p = front.next;
while (p != null){
System.out.println(p.data);
p = p.next;
}
}
//销毁一个已存在的队列
public void clear(){
front.next = rear.next = null;
}
}
二、测试代码如下
public class testLinkQueue {
public static void main(String[] args) {
LinkQueue<Integer> queue = new LinkQueue<>();
int a[] = {23,45,2,6,9,4,87,20};
for(int i = 0;i<a.length;i++){
queue.EnQueue(a[i]);
}
System.out.println("链队列为:");
System.out.println("长度为"+queue.size());
queue.nextOrder();
queue.DeQueue();
System.out.println("链队列为:");
System.out.println("长度为"+queue.size());
queue.nextOrder();
System.out.println("链队列的头元素为:" + queue.getHead());
}
}