package org.loda.structure;
import java.util.Iterator;
/**
*
* @ClassName: Bag
* @Description: 背包
*
* 单纯用来存储元素,只支持添加O(1),迭代操作O(N)
*
* 使用背包的目的是因为他很简单,添加很快,而且能迭代所有元素(无所谓先进后出还是先进先出),不需要更多的功能。
* 在图论中,背包会经常作为里面的一种方便、高效的数据结构而使用
*
* @author minjun
* @date 2015年5月23日 下午7:03:08
*
* @param <E>
*/
public class Bag<E> implements Iterable<E> {
private Node first;
/**
*
* @Title: add
* @Description: 添加元素,最快的添加方式当然是从头开始添加
* @param @param e 设定文件
* @return void 返回类型
* @throws
*/
public void add(E e){
if(e==null)
throw new NullPointerException("添加操作参数不能为空");
Node oldFirst=first;
first=new Node(e);
first.next=oldFirst;
}
private class Node{
E e;
Node next;
public Node(E e){
this.e=e;
}
}
@Override
public Iterator<E> iterator() {
return new BagIterator();
}
private class BagIterator implements Iterator<E>{
//为了保护头结点,这里用一个变量临时充当头结点
private Node temp=first;
@Override
public boolean hasNext() {
return temp!=null;
}
/**'
* 为了快速获取元素,这里会直接取第一个元素,这样,我们的背包结构就成了一个“先进后出”的栈
* 这里不是刻意营造一个栈结构,而是为了保证添加和迭代速度,自然而然使得背包成了一个“栈”
*/
@Override
public E next() {
if(!hasNext())
throw new RuntimeException("没有元素了,你还取什么东西!");
Node oldFirst=temp;
temp=oldFirst.next;
return oldFirst.e;
}
@Override
public void remove() {
throw new RuntimeException("暂时不支持删除操作");
}
}
public static void main(String[] args) {
Bag<Integer> bag=new Bag<Integer>();
bag.add(3);
bag.add(5);
bag.add(1);
bag.add(4);
for(int b:bag){
System.out.println(b);
}
}
}