/** 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 { /** 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; for (int i = 0; i < index; i++) { current = current.next; } current.data = value; } /** 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(); } } }