// 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 { // 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; } ListNode n = new ListNode(value, current.next); current.next = n; } } // Removes the value at the given index. // Pre: 0 <= index < size // Throws a NullPointerException if index > size. public void remove(int index) { if (index == 0) { front = front.next; } else { ListNode current = front; for (int i = 0; i < index - 1; i++) { current = current.next; } current.next = current.next.next; } } // Adds the given element value to the list in sorted order. // Pre: the list is already sorted // Post: the new element is added and the list is still sorted public void addSorted(int value) { if (front == null || value <= front.data) { front = new ListNode(value, front); } else { ListNode current = front; while (current.next != null && current.next.data < value) { current = current.next; } current.next = new ListNode(value, current.next); } } }