import java.util.*;

/**
 * LinkedList
 * implementation of a LinkedList using ListNodes.
 * this implementation is extended by OrderedLinkedList in this lab.
 */

public class LinkedList {
    protected ListNode first;
    protected ListNode last;
    
    public LinkedList() 
    {
        first = null;
        last = null;
    }
    
    public Object getFirst()
    {
        if(first == null)
            throw new NoSuchElementException();
        else
            return first.getValue();
    }
    
    public void addFirst(Object value)
    {
        first = new ListNode(value, first);
        if(last == null)
            last = first;
    }
    
    public Object getLast()
    {
        if(last == null)
            throw new NoSuchElementException();
        else
            return last.getValue();
    }
    
    public void addLast(Object value)
    {
        if(first == null)
            first = last = new ListNode(value, first);
        else
        {
            last.setNext(new ListNode(value, null));
            last = last.getNext();
        }
    }
    
    public int size()
    {
        ListNode temp = first;
        int count = 0;
        while(temp != null)
        {
            temp = temp.getNext();
            count++;
        }
        return count;
    }
    
    public void printList()
    {
        ListNode temp = first;
        while(temp != null)
        {
            System.out.println(temp.getValue() + " ");
            temp = temp.getNext();
        }
    }
    
    public String toString()
    {
        String s = "[";
        ListNode temp = first;
        while(temp != null)
        {
            s += temp.getValue();
            temp = temp.getNext();
            if(temp != null)
                s += ", ";
        }
        s += "]";
        return s;
    }
}
