// CSE 143, Winter 2011, Marty Stepp // A LinkedIntList object stores a list of integers using a series of linked // node objects. We will implement the same methods as ArrayIntList. public class LinkedIntList { private ListNode front; // refers to first node in list (null if empty) // Constructs a new empty list. public LinkedIntList() { front = null; // null front means empty } // Adds the given value to the end of this list. public void add(int value) { if (front == null) { // empty list front = new ListNode(value); } else { // non-empty list; walk to last node ListNode current = front; while (current.next != null) { current = current.next; } // add new node at end of list current.next = new ListNode(value); } } // Inserts the given value into this list at the specified index. // Precondition: 0 <= index <= size // Throws a NullPointerException if index > size. public void add(int index, int value) { if (index == 0) { // insert at front of list front = new ListNode(value, front); } else { // walk to node before the one to insert ListNode current = front; for (int i = 0; i < index - 1; i++) { current = current.next; } ListNode newNode = new ListNode(value, current.next); current.next = newNode; // shorter version of the above code // current.next = new ListNode(value, current.next); } } // Returns the element at the specified index from the list. // Precondition: 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; } }