自己写个支持泛型和迭代的链表队列,接口如下:
代码如下:
有一点需要特别注意,在出队列时,如果队列中只上下一个元素,那么需要将队列的头和尾回归到同一个位置。使队列回归到初始化的状态,否则会报空指针异常。
import java.util.Iterator;
public class LinkedListQueue<T> implements Iterable<T>{
int length;
Node head;
Node tail;
public class Node{
T item;
Node next;
//节点的无参和有参构造方法
public Node() {};
public Node(T item) {
this.item=item;
}
}
//队列的构造方法
public LinkedListQueue() {
head= new Node();
tail=head;
}
public boolean isEmpty() {
return length==0;
}
public int length() {
return length;
}
public void enQueue(T item) {
Node newNode= new Node(item);
tail.next=newNode;
newNode.next=null;
tail=newNode;
length++;
}
public T deQueue() {
if(length==0) {
System.out.println("队列为空,无法出列");
return null;
}
//这里要格外注意,当只剩下最后一个元素出列的时候
//把head和tail在重新关联起来,回到队列刚刚创建时的状态
else if(length==1) {
T result= head.next.item;
length--;
head=tail;
return result;
}
else {
T result=(T) head.next.item;
head.next=head.next.next;
length--;
return result;
}
}
public T getHead() {
T result=(T) head.next.item;
return result;
}
@Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return new QueueIterator();
}
private class QueueIterator implements Iterator<T>{
@Override
public boolean hasNext() {
return length>0;
}
@Override
public T next() {
Node newhead=head;
head=head.next;
length--;
return newhead.next.item;
}
}
}