java实现迭代遍历接口的队列(Queue)

public class Queue<Item> implements Iterable<Item>{
private Node first;
private Node last;
private int N;
private class Node{
    Item item;
    Node next;
}
public boolean isEmpty(){ return first == null;}
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 class AIterator<Item> implements Iterator<Item>{
    private Node ifirst=first;
    @Override
    public boolean hasNext() {
        return ifirst==null;
    }
    @Override
    public Item next() {
        Item item = ifirst.item;
        Node first = ifirst.next;
        return item;
    }

    @Override
    public void remove() {
    }
}
@Override
public Iterator<Item> iterator() {
    return new AIterator();
}

 }

 

你可能感兴趣的:(java实现)