Question: Question. Implement the following Bag by using a LinkedList , i.e., set up an instance variable of type List , fill it in with a

Question.

Implement the following Bag by using a LinkedList, i.e., set up an instance variable of type List, fill it in with a LinkedListat the time of the Bags creation, and use it to store new elements as they come in. Note that the LinkedList can provide a working iterator, so you dont need a private class for the iterator, or the Node class either. Your iterator from LinkedList will have a working remove(), unlike the books iterator, but that's OK.

Write a client program, BagTest, that puts "apple, "pear, and "apple in a Bag, and then counts the apples in the bag. What methods are available on the Bag object in this client program? Please show Bag.java, TestBag.java, and the answer to the question.

Question. Implement the following Bag by using a LinkedList, i.e., set up

ALGORITHM 1.4 Bag import java.util.Iterator; public class Bag implements Iterable // first node in list private Node first; private class Node Item item; Node next; public void add (Item item) { // same as push() in Stack Node oldfirst = first; first = new Node; first.item = item; first.next = oldfirst; public Iterator iterator { return new ListIterator; } private class ListIterator implements Iterator private Node current = first; public boolean hasNext { return current != null; } public void remove { } public Item next Item item = current.item; current = current.next; return item; This Bag implementation maintains a linked list of the items provided in calls to add(). Code for isEmpty and size is the same as in Stack and is omitted. The iterator traverses the list, main- taining the current node in current. We can make Stack and Queue iterable by adding the code highlighted in red to ALGORITHMS 1.1 and 1.2, because they use the same underlying data structure and Stack and Queue maintain the list in LIFO and FIFO order, respectively

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!