队列是一种基于先进先出策略的数据集合。
使用链表以及泛型机制来实现可以达到最优设计目标:
(1)可以处理任意类型的数据;
(2)所需的空间总是和集合的大小成正比;
(3)操作所需的时间总是和集合的大小无关。
1 import java.util.Scanner; 2 import java.util.Iterator; 3 4 public class Queue<Item> implements Iterable<Item>{ 5 6 private class Node{ 7 //LinkedList Node 8 Item item = null; 9 Node next = null; 10 } 11 12 private Node first = null; //head 13 private Node last = null; //tail 14 private int n = 0; //size 15 16 public boolean isEmpty(){ 17 return first == null; 18 } 19 20 public int size(){ 21 return n; 22 } 23 24 public void enqueue(Item item){ 25 Node oldLast = last; 26 last = new Node(); 27 last.item = item; 28 last.next = null; 29 30 if(isEmpty()){ 31 first = last; 32 } 33 else{ 34 oldLast.next = last; 35 } 36 n ++; 37 } 38 39 public Item dequeue(){ 40 Item item = first.item; 41 first = first.next; 42 if(isEmpty()){ 43 last = first; 44 } 45 n --; 46 return item; 47 } 48 49 public Iterator<Item> iterator(){ 50 return new ListIterator(); 51 } 52 53 private class ListIterator implements Iterator<Item>{ 54 private Node current = first; 55 56 public boolean hasNext(){ 57 return current != null; 58 } 59 60 public Item next(){ 61 Item item = current.item; 62 current = current.next; 63 return item; 64 } 65 66 public void remove(){} 67 } 68 69 public static void main(String[] args) { 70 Scanner in = new Scanner(System.in); 71 72 Queue<String> q = new Queue<>(); 73 while(in.hasNext()){ 74 String item = in.next(); 75 if(!item.equals("-")){ 76 q.enqueue(item); 77 } 78 else if(!q.isEmpty()){ 79 System.out.print(q.dequeue() + " "); 80 } 81 } 82 83 System.out.println("(" + q.size() + " left on stack)"); 84 } 85 }
(参考自《Algorithm 4th》)