/****************************************************************************** * Compilation: javac Bag.java * Execution: java Bag < input.txt * Dependencies: StdIn.java StdOut.java * * A generic bag or multiset, implemented using a singly linked list. * * % more tobe.txt * to be or not to - be - - that - - - is * * % java Bag < tobe.txt * size of bag = 14 * is * - * - * - * that * - * - * be * - * to * not * or * be * to * ******************************************************************************/ import java.util.Iterator; import java.util.NoSuchElementException; /** * The {@code Bag} class represents a bag (or multiset) of * generic items. It supports insertion and iterating over the * items in arbitrary order. *

* This implementation uses a singly linked list with a static nested class Node. * See {@link LinkedBag} for the version from the * textbook that uses a non-static nested class. * See {@link ResizingArrayBag} for a version that uses a resizing array. * The add, isEmpty, and size operations * take constant time. Iteration takes time proportional to the number of items. *

* For additional documentation, see Section 1.3 of * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne * * @param the generic type of each item in this bag */ public class Bag implements Iterable { private Node first; // beginning of bag private int n; // number of elements in bag // helper linked list class private static class Node { private Item item; private Node next; } /** * Initializes an empty bag. */ public Bag() { first = null; n = 0; } /** * Returns true if this bag is empty. * * @return {@code true} if this bag is empty; * {@code false} otherwise */ public boolean isEmpty() { return first == null; } /** * Returns the number of items in this bag. * * @return the number of items in this bag */ public int size() { return n; } /** * Adds the item to this bag. * * @param item the item to add to this bag */ public void add(Item item) { Node oldfirst = first; first = new Node(); 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 iterator() { return new LinkedIterator(first); } private class LinkedIterator implements Iterator { private Node current; public LinkedIterator(Node first) { current = first; } public boolean hasNext() { return current != null; } public Item next() { if (!hasNext()) throw new NoSuchElementException(); Item item = current.item; current = current.next; return item; } } /** * Unit tests the {@code Bag} data type. * * @param args the command-line arguments */ public static void main(String[] args) { Bag bag = new Bag(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); bag.add(item); } StdOut.println("size of bag = " + bag.size()); for (String s : bag) { StdOut.println(s); } } }