publicclassLinkQueue<T>{
//结点类
publicclassNode{
public T data;
publicNode next;
publicNode(T obj,Node next){
this.data = obj;
this.next = next;
}
}
privateNode head,front,rear;
publicLinkQueue(){
head =newNode(null,null);
front = rear = head;
size =0;
}
//从队尾入队
publicvoid add(T t)
{
Node s =newNode(t,null);
rear.next = s;
rear = s;
size++;//队列长度+1
}
//从队头出队
public T poll() throws Exception
{
if(rear == front)
thrownewException("under flow!");
Node temp = front.next; //暂存队首,以便返回
front.next = front.next.next;
if(front.next == null) //最后一个元素出队:还要对队尾处理
rear = front;
return temp.data;
}
public boolean isEmpty(){
return front == rear;
}
}
LinkQueue<String> q =newLinkQueue<String>();
q.add("a");
q.add("b");
q.add("c");
q.add("d");
q.add("e");
q.add("f");
q.add("g");
q.add("h");
q.add("i");
q.add("j");
q.add("k");
q.add("l");
q.add("m");
while(!q.isEmpty()){
String temp = q.poll();
System.out.print(temp);
}
输出
abcdefghijklm