算法1.4 背包(Bag)

  1. import java.util.Iterator;
  2. public class Bag<Item> implements Iterable<Item>{
  3. private class Node{
  4. Item item;
  5. Node next;
  6. }
  7. private Node first;
  8. private int N;
  9. public boolean isEmpty(){ return N == 0; }
  10. public int size(){ return N; }
  11. public void add(Item item){
  12. Node oldFirst = first;
  13. first = new Node();
  14. first.item = item;
  15. first.next = oldFirst;
  16. N++;
  17. }//和Stack的push()相同
  18. @Override
  19. public Iterator<Item> iterator(){
  20. return new ListIterator();
  21. }
  22. private class ListIterator implements Iterator<Item>{
  23. private Node current = first;
  24. @Override
  25. public boolean hasNext(){ return current != null;}
  26. @Override
  27. public Item next(){
  28. Item item = current.item;
  29. current = current.next;
  30. return item;
  31. }
  32. @Override
  33. public void remove(){}
  34. }
  35. }

要点

  1. 背包也是FIFO策略,即一个没有pop()的Stack,将push()改名为add();

特点

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