import java.util.NoSuchElementException; public class LinkedList { public LinkedList() { first = null; // last = null; // see the LinkedList class "version B" methods below } public Object getFirst() { if (first == null) throw new NoSuchElementException(); return first.getValue(); } public void addFirst(Object obj) { ListNode newNode = new ListNode(obj, first); first = newNode; } public Object removeFirst() { if (first == null) throw new NoSuchElementException(); Object obj = first.getValue(); first = first.getNext(); return obj; } public Object getLast() { if (first == null) throw new NoSuchElementException(); ListNode temp = first; while (temp.getNext() != null) temp = temp.getNext(); return temp.getValue(); } public void addLast(Object obj) { ListNode newNode = new ListNode(obj, null); ListNode temp = first; while (temp.getNext() != null) temp = temp.getNext(); temp.setNext(newNode); } public Object removeLast() { if (first == null) throw new NoSuchElementException(); if (first.getNext() == null) { Object obj = first.getValue(); first = null; return obj; } ListNode temp = first; ListNode follower = temp; while (temp.getNext() != null) { follower = temp; temp = temp.getNext(); } follower.setNext(null); return temp.getValue(); } // The following "version B" methods would work if the last property // is included in the LinkedList class. /* public Object getLast() { if (first == null) throw new NoSuchElementException(); return last.getValue(); } public void addLast(Object obj) { ListNode newNode = new ListNode(obj, null); if (first == null) { first = newNode; last = newNode; } else { last.setNext(newNode); last = newNode; } } public Object removeLast() { if (first == null) throw new NoSuchElementException(); ListNode temp = first; if (first.getNext() == null) { Object obj = first.getValue(); first = null; last = null; return obj; } while (temp.getNext() != last) { temp = temp.getNext(); } Object obj = last.getValue(); temp.setNext(null); last = temp; return obj; } */ private ListNode first; // private ListNode last; // see the "version B" methods above }