Add the following methods to our SinglyLinkedList class. You MUST completely test out each method that it works for an empty list, one node list and multi node list. You should print the list before and after the operations to show that they work correctly.
removeFirst public Object removeFirst()Removes and returns the first element from this list. Returns: the first element from this list. Throws: NoSuchElementException - if this list is empty. -------------------------------------------------------------------------------- removeLast public Object removeLast()Removes and returns the last element from this list. Returns: the last element from this list. Throws: NoSuchElementException - if this list is empty. ----------------------------------------------------------------------------- addFirst public void addFirst(Object o)Inserts the given element at the beginning of this list. Parameters: o - the element to be inserted at the beginning of this list. -------------------------------------------------------------------------------- addLast public void addLast(Object o)Appends the given element to the end of this list. (Identical in function to the add method; included only for consistency.) Parameters: o - the element to be inserted at the end of this list. -------------------------------------------------------------------------------- getFirst public Object getFirst()Returns the first element in this list. Returns: the first element in this list. Throws: NoSuchElementException - if this list is empty. -------------------------------------------------------------------------------- getLast public Object getLast()Returns the last element in this list. Returns: the last element in this list. Throws: NoSuchElementException - if this list is empty.Now let's make our class Iterable by giving it an iterator method:
Make the following additions/changes to your SinglyLinkedList class.
import java.util.Iterator;
public class SinglyLinkedList implements Iterable<Object>
// Returns an iterator for this collection.
public Iterator<Object> iterator()
{
return new SinglyLinkedListIterator(head);
}
Now we need a SinglyLinkedListIterator class added to our project with the following code:
// Implements an iterator for a SinglyLinkedList.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class SinglyLinkedListIterator implements Iterator <Object>
{
private ListNode nextNode;
// Constructor
public SinglyLinkedListIterator(ListNode head)
{
nextNode = head;
}
public boolean hasNext()
{
return nextNode != null;
}
public Object next()
{
if (nextNode == null)
throw new NoSuchElementException();
Object value = nextNode.getValue();
nextNode = nextNode.getNext();
return value;
}
// Not implemented.
public void remove()
{
throw new UnsupportedOperationException();
}
}
HAVE FUN!!!!!