Skip to content
Snippets Groups Projects
Bag.java 871 B
Newer Older
  • Learn to ignore specific revisions
  • package search;
    
    import java.util.Iterator;
    
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    public class Bag<Integer> implements Iterable<Integer> {
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	private Node first; //pointer to head of linked list
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	
    	private class Node{
    		Integer item;
    		Node next;
    	}
    	
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	/**
    	 * Adds new node to linked list
    	 * @param item the item to be added to the linked list
    	 */
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    	public void add(Integer item){
    		Node oldfirst = first;
    		first = new Node();
    		first.item = item;
    		first.next = oldfirst;
    	}
    	
    
    	@Override
    	public Iterator<Integer> iterator() {
    
    		return new ListIterator();
    	}
    	
    	private class ListIterator implements Iterator<Integer>{
    		
    		private Node current = first;
    		
    		public boolean hasNext(){
    			return current != null;
    		}
    
    Lawrence Chung's avatar
    Lawrence Chung committed
    		public void remove(){
    			current.next = current.next.next;
    		}
    
    		public Integer next(){
    			
    			Integer item = current.item;
    			current = current.next;
    			return item;
    
    Lawrence Chung's avatar
    Lawrence Chung committed