public class MyLinkedList implements MyList { private MyLListNode head = null; class MyLListNode { private int key; private MyLListNode next; MyLListNode (int val) { key = val; next = null; } } MyLinkedList() { head = null; } public void makeEmpty() { head = null; } public boolean isEmpty() { return (head==null); } public void printList() { if (head == null) System.err.println("Empty list"); else { MyLListNode curr = head; System.err.print("LList elements: "); while (curr != null) { System.err.print(curr.key + " "); curr = curr.next; } System.err.println(); } } public int size() { if (head == null) return 0; else { int size = 0; MyLListNode curr = head; while (curr != null) { size++; curr = curr.next; } return size; } } public boolean contains(int key) { if (isEmpty()) return false; else { boolean result = false; MyLListNode curr = head; while ((curr != null) && !result) { if (curr.key == key) result = true; curr = curr.next; } return result; } } public int get(int index) { // should handle out of bounds case with an exception but won't ... if ((index < 0) || (index >= size())) return -1; // silly - but we'll assume only positive keys else { int i = 0; MyLListNode curr = head; while (i < index) { curr = curr.next; i++; } return curr.key; } } public void set(int index, int key) { // should handle out of bounds case with an exception but won't ... if ((index < 0) || (index >= size())) { System.err.println("Error: attempt to set non-existent list item"); return; // silly - but we'll assume only positive keys } else { int i = 0; MyLListNode curr = head; while (i < index) { curr = curr.next; i++; } curr.key = key; } } public void add(int index, int key) { // should handle out of bounds case with an exception but won't ... if ((index < 0) || (index > size())) { System.err.println("Error: attempt to add item out of range"); } else if (index == 0) { MyLListNode newNode = new MyLListNode(key); newNode.next = head; head = newNode; } else { MyLListNode newNode = new MyLListNode(key); MyLListNode prev = head; int i = 1; while (i < index) { prev = prev.next; i++; } newNode.next = prev.next; prev.next = newNode; } } public void remove(int index) { // should handle out of bounds case with an exception but won't ... if ((index < 0) || (index >= size())) { System.err.println("Error: attempt to remove item out of range"); } else if (index == 0) { head = head.next; } else { MyLListNode prev = head; int i = 1; while (i < index) { prev = prev.next; i++; } prev.next = prev.next.next; } } public static void main(String[] args) { MyList l = new MyLinkedList(); l.printList(); System.err.println(l.isEmpty()); System.err.println(l.size()); l.add(0, 3); l.printList(); l.add(0,4); l.add(0,2); l.printList(); System.err.println(l.get(1)); //l.remove(4); l.remove(1); l.printList(); l.add(1,5); l.add(1,6); l.add(l.size(), 7); l.printList(); l.remove(2); l.printList(); } }