// CSE 143, Winter 2009, Marty Stepp // A LinkedIntList object represents a linked list of integer values. public class LinkedIntList { private ListNode front; // reference to front node in list (null if empty) // Constructs a new empty list. public LinkedIntList() { front = null; } // Adds the given value to the end of the list. public void add(int value) { if (front == null) { // adding to an empty list front = new ListNode(value); } else { // adding to the end of an existing list; // traverse to the last node in the list so we can append to it ListNode current = front; while (current.next != null) { current = current.next; } // at this point, current.next == null, // and current refers to the last node current.next = new ListNode(value); } } // Adds the given value at the given index in the list. // Precondition: 0 <= index <= size public void add(int index, int value) { // TODO: implement this } // Removes the element at the given index from the list. // Precondition: 0 <= index < size public void remove(int index) { if (index == 0) { // removing the first element must be handled specially front = front.next; } else { // removing some element further down in the list; // traverse to the node before the one we want to remove ListNode current = front; for (int i = 0; i < index - 1; i++) { current = current.next; } // change its next pointer to skip past the offending node current.next = current.next.next; } } // Returns the integer value at the given index in the list. // Precondition: 0 <= index < size public int get(int index) { // traverse to the node at the given index ListNode current = front; for (int i = 0; i < index; i++) { current = current.next; } return current.data; } }