publicclass <Item> implementsIterable<Item> { private Node<Item> first; privateint N; // number of elements in bag
// helper linked list class privatestaticclassNode<Item> { private Item item; private Node<Item> next; }
/** * Initializes an empty bag. */ public(){ first = null; N = 0; }
/** * Returns true if this bag is empty. * * @return <tt>true</tt> if this bag is empty; * <tt>false</tt> otherwise */ publicbooleanisEmpty(){ return first == null; }
/** * Returns the number of items in this bag. * * @return the number of items in this bag */ publicintsize(){ return N; }
/** * Adds the item to this bag. * * @param item the item to add to this bag */ publicvoidadd(Item item){ Node<Item> oldfirst = first; first = new Node<Item>(); first.item = item; first.next = oldfirst; N++; }
/** * Returns an iterator that iterates over the items in this bag in arbitrary order. * * @return an iterator that iterates over the items in this bag in arbitrary order */ public Iterator<Item> iterator(){ returnnew ListIterator<Item>(first); }
// an iterator, doesn't implement remove() since it's optional privateclassListIterator<Item> implementsIterator<Item> { private Node<Item> current;
publicListIterator(Node<Item> first){ current = first; }
publicbooleanhasNext(){ return current != null; } publicvoidremove(){ thrownew UnsupportedOperationException(); }
public Item next(){ if (!hasNext()) thrownew NoSuchElementException(); Item item = current.item; current = current.next; return item; } }
/** * Unit tests the <tt>Bag</tt> data type. */ publicstaticvoidmain(String[] args){ Bag<String> bag = new Bag<String>(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); bag.add(item); }
StdOut.println("size of bag = " + bag.size()); for (String s : bag) { StdOut.println(s); } } }
stack and queue are similar.
array implementation resizing array: Q: how to grow array? A: if array is full, create a new array of twice the size, and copy items
近期评论