Write a Bag class which implements this API The class mainta
Write a Bag class which implements this API. The class maintains a linked list in LIFO order. Alinked list is a recursive data structure that is either empty (null) or a reference to a node having a generic item and a reference to a linked list.
Here is the beginning of the code to get you started.
public class Bag<Item> implements Iterable<Item> {
private int N; // number of elements in bag
private Node first; // beginning of bag
// linked list class
private class Node {
private Item item;
private Node next;
}
// include:
// check for an empty stack
// code that returns the size of bag
// code for adding item to bag
// test client
If the file tiny.txt contains the following:
S O R T E X A M P L E
then the output would be:
java Bag <tiny.txt
size of bag = 11
E
L
P
M
A
X
E
T
R
O
S
Solution
public class Bag<Item> implements Iterable<Item> {
private int N; // number of elements in bag
private Node first; // beginning of bag
// linked list class
private class Node {
private Item item;
private Node next;
Node(Item item, Node n){
item = item;
next = n;
}
Node(Item item)
{
this(item, null);
}
private Node head;
private Node last;
public Bag(){
head = null;
last = null;
}
// isempty method
public boolean isEmpty(){
return head == null;
}
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
public void add(Item val)
{
if (isEmpty())
{
first = new Node(val);
last = first;
}
else
{
// Adding to existing list
last.next = new Node(val);
last = last.next;
}
}
}

