前两篇文章采用数组形式构造队列,现在用链表构造队列
链式队列基本上和链表类似,基本如下:
rear指针始终指向链表最后一个元素
front指针始终指向链表第一个元素
代码如下:
public class LinkQueue<T> {
private Node front;//队头指针
private Node rear;//队尾指针
private int size = 0;
public LinkQueue(){
}
//-----进入队列算法-------
public boolean enQueue(T data){
if(data == null)
return false;
Node node = new Node(data);
if(front == null){
front = node;
rear = front;
size++;
}else{
rear.next = node;
rear = rear.next;
size++;
}
return true;
}
//------出队列算法---------
public T deQueue() throws Exception{
if(front == null)
throw new Exception("LinkQueue is empty ");
T ret = front.data;
front = front.next;
size--;
return ret;
}
//------队列中元素个数-----------
public int getSize(){
return size;
}
//-------判断队列是否为空------------
public boolean isEmpty(){
return (front == null)? true:false;
}
//------打印队列------------
public void display() throws Exception{
if(isEmpty())
throw new Exception("LinkQueue is empty ");
Node current = front;
while(current != null){
System.out.println(current.data);
current = current.next;
}
}
class Node{
T data;
Node next;
public Node(){}
public Node(T data){
this.data = data;
}
}
public static void main(String[] args) throws Exception{
LinkQueue linkQueue = new LinkQueue();
for(int i=1;i<=100;i++)
linkQueue.enQueue(i);
System.out.println("元素数量:"+ linkQueue.getSize());
System.out.println("**************************");
for(int i=1;i<=99;i++)
linkQueue.deQueue();
System.out.println("元素数量:"+ linkQueue.getSize());
System.out.println("**************************");
for(int i=101;i<=200;i++)
linkQueue.enQueue(i);
System.out.println("元素数量:"+ linkQueue.getSize());
System.out.println("**************************");
}
}