// Helene Martin, CSE 143 // A LinkedIntList object represents an ordered list of linked nodes. // Like ArrayIntList, LinkedIntList is an implementation of the List ADT. public class LinkedIntList { private ListNode front; // Constructs an empty list. public LinkedIntList() { front = null; } // Builds a new LinkedIntList with the specified number of nodes. // Node values start at 0 and increase in value. // pre: n >= 0 public LinkedIntList(int n) { for (int i = n - 1; i >= 0; i--) { //ListNode temp = new ListNode(i, front); //front = temp; front = new ListNode(i, front); } /* We wrote out some specific lines of code for the case where n = 3 and the list should be [0, 1, 2] to help us see the pattern n = 3 ListNode temp = new ListNode(2, front); // n -1 front = temp; ListNode temp2 = new ListNode(1, front); // n-2 front = temp2 ListNode temp3 = new ListNode(0, front); front = temp3; */ } // Add the given value to the end of the list. public void add(int value) { if (front == null) { front = new ListNode(value); } else { // list wasn't empty; find the back // (note: this is inefficient. We could keep a reference to the last node) ListNode current = front; while (current.next != null) { current = current.next; } current.next = new ListNode(value); } } // Adds a value at a given index. // pre: 0 <= index <= size // Throws a NullPointerException if 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; } ListNode temp = new ListNode(value, current.next); current.next = temp; // also ok: current.next = new ListNode(value, current.next); } } // Adds the given value in sorted order, duplicates allowed. // pre: list is sorted // post: list is sorted 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; } //ListNode temp = new ListNode(value, current.next); //current.next = temp; current.next = new ListNode(value, current.next); } } // Returns the value at a given index // pre: 0 <= index < number of nodes; front != null // throws NullPointerException if index > size. public int get(int index) { ListNode current = front; for (int i = 0; i < index; i++) { current = current.next; } return current.data; } // 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; } } }