import java.util.*; public class LinkedIntList { private ListNode front; public LinkedIntList() { front = null; } // Removes and returns the first value. // Throws a NoSuchElementException on empty list. public int remove() { if (front == null) { throw new NoSuchElementException(); } else { int result = front.data; front = front.next; return result; } } // Removes value at given index from list. // Precondition: 0 <= index < size() public void remove(int index) { if (index == 0) { // special case: removing first element front = front.next; } else { // removing from elsewhere in the list ListNode current = front; for (int i = 0; i < index - 1; i++) { current = current.next; } current.next = current.next.next; } } // Adds given value to list in sorted order. // Precondition: Existing elements are sorted public void addSorted(int value) { if (front == null || value <= front.data) { // insert at front of list front = new ListNode(value, front); } else { // insert in middle of list ListNode current = front; while (current.next != null && current.next.data < value) { current = current.next; } current.next = new ListNode(value, current.next); } } // Gets the item in the list at the given index public int get(int index) { ListNode current = front; for (int i = 0; i < index; i++) { current = current.next; } return current.data; } // Adds the given value to the end of the list public void add(int value) { if (front == null) { front = new ListNode(value); } else { ListNode current = front; // find the last node of the list while (current.next != null) { current = current.next; } current.next = new ListNode(value); } } // Returns a 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; } } }