Java实现Queue类
import java.util.Iterator;import java.util.NoSuchElementException;import java.util.Scanner;public class Queue- implements Iterable
- { private int N; private Node
- first; private Node
- last; private static class Node
- { private Item item; private Node
- next; } public Queue() { first = null; last = null; N = 0; } public boolean isEmpty() { return first == null; } public int size() { return N; } public Item peek() { if(isEmpty()) throw new NoSuchElementException("Queue underflow"); return first.item; } 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() { if(isEmpty()) throw new NoSuchElementException("Queue underflow"); Item item = first.item; first = first.next; N --; if(isEmpty()) last = null; return item; } public String toString() { StringBuilder s = new StringBuilder(); for(Item item : this) s.append(item + " "); return s.toString(); } public Iterator
- iterator() { return new ListIterator
- (first); } private class ListIterator
- implements Iterator
- { private Node
- current; public ListIterator(Node
- first) { current = first; } public boolean hasNext() { return current != null; } public void remove() { throw new UnsupportedOperationException(); } public Item next() { if(!hasNext()) throw new NoSuchElementException(); Item item = current.item; current = current.next; return item; } } public static void main(String[] args) { Queue
q = new Queue (); Scanner in = new Scanner(System.in); while(in.hasNext()) { String item = in.next(); if(!item.equals("-")) q.enqueue(item); else if(!q.isEmpty()) System.out.println(q.dequeue()); System.out.println("(" + q.size() + " left on queue)"); } }}