# 链表之初级集合(背包)实现

23 阅读2分钟

### 背包

#### 设计思路与实现

``````package com.magic.school.hogwarts.design.algorithm.api.one.bag;

import org.jetbrains.annotations.NotNull;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Bag<Item> implements Iterable<Item> {
/**
* 元素数量
*/
private int size;
/**
* 首结点
*/
private Node first;

/**
* 栈结构保存数据
*/
private class Node {
Item item;
Node next;
}

/**
* 为实现遍历我们用内部类实现Iterator接口
*/
private class BagIterator implements Iterator<Item>{
private Node current = first;
@Override
public boolean hasNext() {
return current!=null;
}

@Override
public Item next() {
if (!hasNext()){throw new NoSuchElementException("Bag is Empty!");}
Item item = current.item;
current = current.next;
return item;
}
}

/**
* 添加元素
* @param item
*/
//从首结点添加
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
size++;
}

/**
* 获取背包内元素数量
* @return
*/
public int size(){return size;}

/**
* 是否null背包
* @return
*/
public boolean isEmpty(){
return first == null;
}

/**
* 通过iterator遍历元素
* @return
*/
@Override
public Iterator<Item> iterator(){
return new BagIterator();
}

public static void main(String[] args) {
Bag<Integer> bag = new Bag<>();
for (int i = 0; i < 1000; i++) {
}
Iterator<Integer> iterator = bag.iterator();
int sum = 0;
while (iterator.hasNext()) {
int num = iterator.next();
System.out.println(num);
sum += num;
}
System.out.println("============================");
System.out.println("sum: " + sum);
}
}
``````