// Hunter Schafer, CSE 143 // This class represents a list of integers public class LinkedIntList { private ListNode front; // Constructs an empty list public LinkedIntList() { front = null; } // Returns a String representation of this list // surrounded by square brackets with the elements in order // separated by commas. // Example: [1, 2, 3, 4] public String toString() { // commented out code is code for array // if (size == 0) { if (front == null) { return "[]"; } // String result = "[" + elementData[0]; String result = "[" + front.data; // int i = 1; ListNode current = front.next; // while (i < size) { while (current != null) { // result += ", " + elementData[i]; result += ", " + current.data; // i = i + 1; current = current.next; } result += "]"; return result; } // Adds the given value to the end of this list public void add(int value) { if (front == null) { front = new ListNode(value); } else { ListNode current = front; while (current.next != null) { current = current.next; } current.next = new ListNode(value); } } // pre: 0 <= index <= size // post: Adds the given value at the given index, shifting subsequent // values to the right public void add(int index, int value) { if (index == 0) { // Longer solution // ListNode temp = new ListNode(value); // temp.next = front; // front = temp // Shorter solution, both are fine front = new ListNode(value, front); } else { ListNode current = front; for (int i = 0; i < index - 1; i++) { current = current.next; } // Long solution, definitely works // ListNode temp = new ListNode(value); // temp.next = current.next; // current.next = temp; // Shorter solution, both are fine current.next = new ListNode(value, current.next); } } }