// CSE 143, winter 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; } // Add the given value to the end of the list. 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. public int get(int index) { 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. public void add(int index, int value) { 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); } } }