import java.util.NoSuchElementException; // CSE 143, Autumn 2013 // 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; } // 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); } } // Adds a value at a given index. // pre: 0 <= 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); } } // removes and returns the first element in the list // Pre: size > 0 public int remove() { if (front == null) { throw new NoSuchElementException(); } int value = front.data; front = front.next; return value; } // Removes the value at the given index. // Pre: 0 <= 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; } } // Returns the element at the specified index from the list. // Precondition: 0 <= index < size public int get(int index) { ListNode current = front; for(int i = 0; i < index; i++) { current = current.next; } return current.data; } // pre: list is sorted // post: list is sorted and the given value is added in sorted order, duplicates allowed. 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); } } // Returns a comma-separated String representation of this list. public String toString() { if (front == null) { return "[]"; } else { String result = "[" + front.data; ListNode current = front.next; while (current != null) { result += ", " + current.data; current = current.next; } result += "]"; return result; } } }