先进先出队列


数组实现(Ex1_3_14)

  1. import java.util.Iterator;
  2. public class ArrayQueue<Item> implements Iterable<Item> {
  3. private Item[] a = (Item[]) new Object[1];
  4. private int N = 0;
  5. private int head = 0;//出队元素索引
  6. private int tail = 0;//入队元素索引
  7. public boolean isEmpty() {
  8. return N > 0;
  9. }
  10. public int size() {
  11. return N;
  12. }
  13. public void resize(int max) {
  14. Item[] temp = (Item[]) new Object[max];
  15. for (int i = 0; i < N; i++) {
  16. temp[i] = a[i];
  17. }
  18. a = temp;
  19. }
  20. public void enqueue(Item item) {
  21. if (N == a.length) resize(2 * a.length);
  22. a[N++] = item;
  23. tail++;
  24. }//从队尾插入
  25. public Item dequeue() {
  26. Item item = a[--N];
  27. if (N == a.length / 4) resize(a.length / 2);
  28. head++;
  29. return item;
  30. }//从队首离开
  31. @Override
  32. public Iterator<Item> iterator() { return new ArrayIterator(); }
  33. private class ArrayIterator implements Iterator<Item> {
  34. private int i = head;
  35. @Override
  36. public boolean hasNext() { return i <= tail; }
  37. @Override
  38. public Item next() { return a[i++]; }
  39. @Override
  40. public void remove() { }
  41. }
  42. }

要点

  1. 两个int变量,head和tail作为索引,当元素入列,进入队尾,tail++;当元素出列,离开队首,head++,通过这种方法保证只有head和tail间的元素可以被操作

算法1.3 先进先出队列(链表实现)

  1. import java.util.Iterator;
  2. public class Queue<Item> implements Iterable<Item>{
  3. private Node first;
  4. private Node last;
  5. private int N;
  6. private class Node{
  7. Item item;
  8. Node next;
  9. }
  10. public boolean isEmpty(){ return N == 0 ;}
  11. public int size(){ return N;}
  12. public void enqueue(Item item){
  13. Node oldLast = last;
  14. last = new Node();
  15. last.item = item;
  16. last.next = null;
  17. if(isEmpty()) first = last ;//链表为空,first,last同时指向新节点
  18. else oldLast.next = last;
  19. N++;
  20. }
  21. public Item dequeue(){
  22. Item item = first.item;
  23. first = first.next;
  24. if(isEmpty()) last = null;//链表为空,更新last
  25. N--;
  26. return item;
  27. }
  28. @Override
  29. public Iterator<Item> iterator(){ return new QueueIterator(); }
  30. private class QueueIterator implements Iterator<Item> {
  31. private Node current = first;
  32. @Override
  33. public boolean hasNext(){ return current != null;}
  34. @Override
  35. public Item next(){
  36. Item item = current.item;
  37. current = current.next;
  38. return item;
  39. }
  40. @Override
  41. public void remove(){}
  42. }
  43. }

要点

  1. 定义内部类Node
  2. Node型的实例变量first和last分别指向最早和最晚添加进的节点
  3. enqueue()中,创建节点后,链表为空时,first和last同时指向新节点
  4. dequeue()中,删除节点后,链表为空时,last为null

特点

  1. 可以处理任何类型的数据
  2. 所需空间和集合大小成正比
  3. 操作所需时间和集合大小无关