// CSE 143, Summer 2012 // A LinkedIntList object is a list of integers represented as linked nodes. // LinkedIntList implements the same methods as ArrayIntList but with // different runtime efficiencies. public class LinkedIntList { private ListNode front; // Constructs an empty list public LinkedIntList () { front = null; } // The value will be added at the end of the list, // the size of the list will be one greater public void add (int value) { if (front == null) { front = new ListNode (value); } else { // list wasn't empty; find the back // (note: this is inefficient. We could keep a reference to the last node) ListNode current = front; while (current.next != null) { current = current.next; } current.next = new ListNode (value); } } // Returns the value at a given index. // pre: 0 <= index < size // Throws a NullPointerException if index > size or index < 0. public int get (int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("index was out of bounds"); } ListNode current = front; for (int i = 0; i < index; i++) { current = current.next; } return current.data; } // Adds a value at a given index. // Pre: 0 <= index <= size // Throws a NullPointerException if index > size or index < 0 public void add (int index, int value) { if (index < 0 || index >= size) { throw new IllegalArgumentException("index was out of bounds"); } else if (index == 0) { front = new ListNode (value, front); } else { ListNode current = front; for (int i = 0; i < index - 1; i++) { current = current.next; } current.next = new ListNode (value, current.next); } } }