/** * LinkedIntList is a class that represents a LinkedList with int data. Stores a * reference to the front of the LinkedList. * * @author Adam Blank */ public class LinkedIntList { private static class ListNode { final int data; ListNode next; /** Creates a terminal ListNode with data as its data. */ public ListNode(int data) { this(data, null); } /** * Creates a ListNode with data as its data and next as the node it * points to. */ public ListNode(int data, ListNode next) { this.data = data; this.next = next; } } /** Stores the front of the LinkedIntList */ private ListNode front; /** Stores the size of the LinkedIntList */ private int size; /** Creates a new empty LinkedIntList */ public LinkedIntList() { this.front = null; } /** * Constructs a String representation of the LinkedIntList. For example, * "[1, 2, 3]". */ public String toString() { String result = "["; ListNode current = this.front; // Process all but the last element of the LinkedList while (current != null && current.next != null) { result += current.data + ", "; current = current.next; } // Process the last element (if one exists) if (current != null) { result += current.data; } return result + "]"; } /** Appends value to the end of the LinkedIntList. */ public void add(int value) { if (this.front == null) { this.front = new ListNode(value); } else { ListNode current = this.front; while (current.next != null) { current = current.next; } current.next = new ListNode(value); } this.size++; } /** Returns the size of the LinkedIntList */ public int size() { return this.size; } /** * Returns the data at index. pre: 0 <= index <= size, otherwise throws * IllegalArgumentException */ public int get(int index) { checkIndex(index); ListNode current = this.front; for (int i = 0; i < index; i++) { current = current.next; } return current.data; } /** * Sets the data at index to value. pre: 0 <= index <= size, otherwise * throws IllegalArgumentException */ public void set(int index, int value) { checkIndex(index); ListNode current = this.front; if (index == 0) { this.front = new ListNode(value, this.front.next); } else { for (int i = 0; i < index - 1; i++) { current = current.next; } current.next = new ListNode(value, current.next.next); } } public void addSorted(int value) { // insert at front if (this.front == null || this.front.data > value) { this.front = new ListNode(value, this.front); } else { // insert in middle // current.next.data > value ListNode current = this.front; while (current != null && current.next != null && current.next.data < value) { current = current.next; } current.next = new ListNode(value, current.next); } // insert at end } /** * Checks that index is within valid bounds for the LinkedIntList. pre: 0 <= * index <= size, otherwise throws IllegalArgumentException */ private void checkIndex(int index) { if (index < 0 || index >= this.size) { throw new IllegalArgumentException(); } } }