/***************************************************************** * Bag class implemented with a linked list - data are generic * Roughly based on bag in text by Michael Main but simplified * @author Beth Katz * @version March 2008 *****************************************************************/ public class BagLL implements Cloneable { // class invariant // - there are two instance variables: head and itemCount // - head is head reference to a linked list containing // String data; null if there are no items // - itemCount is how many items are in the list private Node head; private int itemCount; // text calls this manyNodes /** * Constructs an empty bag */ public BagLL( ) { head = null; itemCount = 0; } /** * Add item to bag * @param item * item to be added */ public void add(E item) { head = new Node(item, head); itemCount++; } /** * Removes target from the bag returning whether it was successful * @param target * the item to be removed * @return * whether or not removal was successful */ public boolean remove(E target) { Node cursor = head; while (cursor != null && !(cursor.getData( )).equals(target)) { cursor = cursor.getLink( ); } if (cursor == null) { // not found return false; } else { // move value from head here and chop off head // know there is head because target was found cursor.setData(head.getData( )); head = head.getLink( ); itemCount--; return true; } } /** * Returns a separate copy of this BagLLstring that will appear * to be indistinguishable from the original but separate * Follows pattern on p. 83 of text * @postcondition * The returned BagLLstring is a separate copy of this BagLLstring */ public BagLL clone( ) { BagLL answer; try { answer = (BagLL) super.clone( ); // unavoidable warning - ignore // make a separate copy Node cursor, answerCursor; if (head != null) { // have something to copy // make front of answer list answer.head = new Node(head.getData( ), null); answerCursor = answer.head; cursor = head.getLink( ); // move to next node while (cursor != null) { answerCursor.setLink(new Node(cursor.getData( ), null)); answerCursor = answerCursor.getLink( ); cursor = cursor.getLink( ); } } } catch (CloneNotSupportedException e) { throw new RuntimeException("This class does not implement Cloneable."); } return answer; } /** * Returns a neat horizontal string representation of the * bag's contents * @return * string of bag contents */ public String toString( ) { Node cursor; String answer = "#Items=" + itemCount + " Contents: "; for (cursor = head; cursor != null; cursor = cursor.getLink( )) { answer += cursor.getData( ) + " "; } return answer; } }