1. 程式人生 > >演算法——先進先出佇列

演算法——先進先出佇列

public class Queue<Item> implements Iterable<Item> {

    private Node first;
    private Node last;
    private int N;
    private class Node{
        Item item;
        Node next;
    }
    public int size(){
        return N;
    }

    public boolean isEmpty(){
        return first == null
; } 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; } @Override public Iterator<Item> iterator() { return new ListIterator(); } public class ListIterator implements Iterator<Item>{ private Node current = first; @Override public
boolean hasNext() { return current != null; } @Override public Item next() { Item item = current.item; current = current.next; return item; } @Override public void remove() { throw new UnsupportedOperationException(); } } }

這裡要注意特殊情況,當入佇列的時候,如果為空,那要first = last,出佇列的時候,如果為空,要設定last為空。