背包是一种不支持从中删除元素的集合数据类型---其作用就是帮助用例收集元素并迭代遍历所有收集到的元素。迭代的顺序不确定且与用例无关。
基于链表
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Bag<Item> implements Iterable<Item> {
// 链表
private static class Node<Item>{
private Item item;
private Node<Item>next;
}
private Node<Item>first;
private int n;
public Bag() {
first = null;
n = 0;
}
public boolean isEmpty(){
return first == null;
}
public int size(){
return n;
}
private void add(Item item){
Node<Item>oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}
@Override
public Iterator<Item> iterator() {
return new ListIterator<Item>(first);
}
private class ListIterator<Item> implements Iterator<Item>{
private Node<Item> current;
public ListIterator(Node<Item> first) {
this.current = first;
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Item next() {
if (!hasNext())throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
调用
public static void main(String[] args){
Bag<Double> numbers = new Bag<>();
Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < 10; i++) {
int a = random.nextInt(100);
System.out.println(a);
numbers.add((double) a);
}
int N = numbers.size();
double sum = 0.0;
for (double x:numbers) {
sum += x;
}
System.out.print(sum);
}
网友评论