アルゴリズム論——カスタムデータ構造:バックパック(Bag)


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);
		}
	}
}