QueueNode(将书中后续的Iterable补全)

it2022-05-06  0

package 数据结构.Queue; import java.util.Iterator; public class QueueNode<Item> implements Iterable { private class Node{ Item item; Node next; } Node first; Node last; int N=0; public int size(){ return N; } public boolean isEmpty(){ return N==0; } public void enqueue(Item item){ Node oldfirst=last; last=new Node(); last.item=item; last.next=null; if (isEmpty()) { first=last; } else{ oldfirst.next=last; } N++; } public Item dequeue(){ Item item =first.item; first=first.next; //当注意对象的引用变量是多个时,要注意剩下的引用变量会使得对象无法被回收。 if (isEmpty())last=null; N--; return item; } @Override public Iterator iterator() { return new QueueNodeIterator(); } private class QueueNodeIterator<Item> implements Iterator<Item> { Node temp =first; int j=N; @Override public boolean hasNext() { return j>0; } @Override public Item next() { Item item=(Item) temp.item; temp = temp.next; j--; return item; } @Override public void remove() { } } }

最新回复(0)