PreLab 9: Bags and Linked Lists

  1. Consider the TestBag program, which uses the ArrayBag class.
    1. What will this print?

    2. Add code to the end of this program that does the following:
      1. Creates a new bag, bag3, that contains everything in bag1 and bag2 combined.
      2. Reads in a string from the user and checks to see if that string is in bag3; prints an appropriate message.
      3. Removes a random item from bag3 and adds that item to bag1.
      4. Creates a new, empty bag (bag4).
      5. Adds everything in bag1 to bag4.
      6. Checks to see if bag1 and bag4 contain the same elements; prints an appropriate message.
      7. Repeatedly removes and prints random items from bag4 until it is empty.

  2. Consider the LinearNode class that we discussed in class. Assume that variable front is of type LinearNode, and that it points to a list containing at least one node.
    1. What does the following code do?
      LinearNode newNode = new LinearNode("whatever");
      LinearNode temp = front;
      while (temp.getNext() != null)
          temp =  temp.getNext();

    2. What would the code above do if the list were empty? Explain.

    3. Write code to print each element in the list.

    4. Write code that creates a new node and makes it be the second node in the list.