X307: LinkedBag difference

Write a LinkedBag<T> member method called difference() that takes a bag as an argument, and returns a new bag that contains all the elements that are in the first bag but not in the second. Your difference() method implementation will be inserted/compiled inside the LinkedBag<T> code available to you through the example configured assignment ExLinkedBagsJUnit that you can download in Eclipse (the class name has been shortened in this question to "LinkedBag"). The author's source code is also available online.

The member fields your method implementations may access/change are:

/**
 * A class of bags whose entries are stored in a chain of linked nodes.
 * 
 * @author Frank M. Carrano
 * @author Timothy M. Henry
 * @version 4.0
 */
public final class LinkedBag<T> implements BagInterface<T>
{
    private Node firstNode;  // Reference to first node
    private int numberOfEntries;
    ...
}

Your implementation code for this problem may also access/invoke any of the Bag API methods. (Your solution code may also include helper methods.)

The difference() member you must write might be used like this:

LinkedBag<String> bag1 = new LinkedBag<String>();
LinkedBag<String> bag2 = new LinkedBag<String>();
bag1.add("a");
bag1.add("b");
bag1.add("c");
bag1.add("c");
bag2.add("a");
bag2.add("c");
bag2.add("d");
LinkedBag<String> bag3 = bag1.difference(bag2);
// returns a bag containing: b, c
LinkedBag<String> bag4 = bag2.difference(bag1);
// returns a bag containing: d

Write your implementation of difference() below.

Your Answer:

Feedback

Your feedback will appear here when you check your answer.