背包

背包是一种不支持从中删除元素的数据集合。它的目的是帮助用例收集元素并迭代遍历所有收集到的元素。迭代遍历的顺序没有要求(实现代码中是后进先出)。

使用链表以及泛型机制来实现可以达到最优设计目标:

  (1)可以处理任意类型的数据;

  (2)所需的空间总是和集合的大小成正比;

  (3)操作所需的时间总是和集合的大小无关。

 1 import java.util.Iterator;
 2 import java.util.Scanner;
 3 
 4 public class Bag<Item> implements Iterable<Item> {
 5     private class Node{
 6         Item item;
 7         Node next;
 8     }
 9 
10     private Node first = null;
11     private int n = 0;
12 
13     public boolean isEmpty(){
14         return first == null;
15     }
16 
17     public int size(){
18         return n;
19     }
20 
21     public void add(Item item){
22         Node oldFirst = first;
23         first = new Node();
24         first.item = item;
25         first.next = oldFirst;
26         n ++;
27     }
28 
29     public Iterator<Item> iterator(){
30         return new ListIterator();
31     }
32 
33     private class ListIterator implements Iterator<Item>{
34         private Node current = first;
35 
36         public boolean hasNext(){
37             return current != null;
38         }
39 
40         public Item next(){
41             Item item = current.item;
42             current = current.next;
43             return item;
44         }
45 
46         public void remove(){}
47     }
48 
49 }

 (参考自《Algorithm 4th》)

原文地址:https://www.cnblogs.com/7hat/p/3718139.html