定义
Java
import java.util.Iterator;
public class Queue<Item> implements Iterable<Item> {
private Node first;// 指向最早添加的结点的链接
private Node last;// 指向最近添加的结点的链接
private int N;// 队列中的元素数量
public boolean isEmpty() {
return null == first;// 或:0 == N
}
public int size() {
return N;
}
// 向表尾添加元素
public void enqueue(Item item) {
Node oldlast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
}
// 从表头删除元素
public Item dequeue() {
Item item = first.item;
first = first.next;
if (isEmpty()) last = null;
N--;
return item;
}
public Iterator<Item> iterator() {
return new ListIterator();
}
private class Node {
// 定义了结点的嵌套类
Item item;
Node next;
}
private class ListIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() {
return null != current;
}
public void remove() {
}
public Item next() {
Item item = current.item;
current = current.next;
return item;
}
}
}
public class Test {
public static void main(String[] args) {
String[] ss = {"to", "be", "or", "not", "to", "-", "be", "-", "-", "that", "-", "-", "-", "is"};
Queue<String> q = new Queue<String>();
for (String s : ss) {
if (!s.equals("-")) {
q.enqueue(s);
} else {
System.out.print(q.dequeue() + " ");
}
}
System.out.println("(" + q.size() + " left on queue)");
}
}
to be or not to be (2 left on queue)