// Erika Wolfe, CSE 143 // This class represents a list of integers // Note that LinkedIntList(int n) and addSorted(int value) // would not likely be included in a real LinkedIntList // implementation, but are good examples to practice // LinkedIntList manipulation. public class LinkedIntList { private ListNode front; // Constructs an empty list public LinkedIntList() { front = null; } // post: constructs a new list with the values // [n, n-1, ..., 1, 0] public LinkedIntList(int n) { front = null; // we started by writing out each line explicitly // front = new ListNode(0, front); // front = new ListNode(1, front); // temp = new ListNode(2, front); for (int i = 0; i <= n; i++) { // you could also write this with a temp variable // ListNode temp = new ListNode(i, front); // front = temp; front = new ListNode(n - i, front); } } // pre : list is in sorted (non-decreasing) order // post: given value inserted into list so as to preserve sorted order public void addSorted(int n) { // the order of the tests is important! if (front == null || front.data > n) { front = new ListNode(n, front); } else { ListNode current = front; // robust test sensitive test while (current.next != null && current.next.data < n) { current = current.next; } current.next = new ListNode(n, current.next); } } // pre: 0 <= index <= size // post: inserts the given value at the given index, shifting subsequent // values right public void add(int index, int value) { if (index == 0) { front = new ListNode(value, front); } else { // insert in middle/end; walk to node before the one to insert ListNode current = front; for (int i = 0; i < index - 1; i++) { current = current.next; } current.next = new ListNode(value, current.next); } } // post: appends 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; while (current.next != null) { current = current.next; } current.next = new ListNode(value); } } }