继续复习之前看过的内容......
背包
背包的定义
背包是一种不支持从中删除元素的集合数据类型,目的是帮助用例收集元素并迭代所有收集到的元素,也是检查背包是否为空,或者获取背包中元素的数量。
背包的实现
import java.util.Iterator;
//定义泛型背包类
public class Bag<Item> implements Iterable<Item>{
private Node<Item> first; // 背包的开始
private int n; // 背包中元素的个数
//背包节点类
private class Node<Item> {
Item item; //参数
Node next; //
}
/**
* 初始化空背包
*/
public Bag() {
first = null;
n = 0;
}
/**
* 如果背包为空返回True
*
* @return {@code true} 如果背包为空
* @return {@code false} 否则
*/
public boolean isEmpty() {
return first == null;
}
/**
* 返回背包中元素的个数
*
* @return 背包中元素的个数
*/
public int size() {
return n;
}
/**
* 添加 item 到背包
*
* @param 被添加进背包的item
*/
public void add(Item item) {
Node<Item> oldFirst = first;
first = new Node<Item>();
fitst.item = item;
first.next = oldFirst;
n++;
}
/**
* 返回一个迭代器,该迭代器按任意顺序遍历袋子中的项。
*
* @return 一个迭代器,它以任意顺序遍历这个袋子中的项
*/
public Iterator iterator() {
return new ListIterator<Item>(first);
}
// 迭代器,没有实现remove(),因为它是可选的
private class ListIterator<Item> {
private Node<Item> current;
public ListIterator(Node<Item> 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;
}
}
/**
* 单元测试 {@code Bag} 数据类型。
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Bag<String> bag = new Bag<String>();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
bag.add(item);
}
StdOut.println("size of bag = " + bag.size());
for (String s : bag) {
StdOut.println(s);
}
}
}
以上代码按照 Robert Sedgewick的源码的结构编写,大师的代码看起来就是舒服。