class Node { Object element; Node next; public Node(Object o, Node next) { this.element = o; this.next = next; } // Let's skip all the set and get methods to keep it short } public class SinglyLinkedList { Node head; // constructor creates an empty list public SinglyLinkedList () { head = null; } // a method to insert at the head of the list public void insert(Object o){ Node newHead = new Node(o, head); head = newHead; } // a method to remove the head of the list public void remove(){ if (head == null) return; else head = head.next; } // a method to check if the list contains an element o public boolean contains (Object o) { if (head == null) return false; if (head.element.equals(o)) return true; Node current = head; while (current.next != null) { current = current.next; if (current.element.equals(o)) return true; } return false; } public Object get(int i) throws BadIndexException { if (i < 0 ) throw new BadIndexException(); if (head == null) throw new BadIndexException(); if (i == 0) return head.element; Node current = head; while (current.next != null) { current = current.next; i--; if (i == 0) return current.element; } throw new BadIndexException(); } // just for illustration; public static void main (String[] args) throws BadIndexException { SinglyLinkedList l = new SinglyLinkedList(); String[] numbers = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; System.out.println("Adding ten numbers"); for (int i = 0; i < numbers.length; i++) { l.insert(numbers[i]); } Node current = l.head; while (current != null) { System.out.print(current.element + " "); current = current.next; } System.out.println(); System.out.println("Does it contain 0?"); System.out.println(l.contains("0")); System.out.println("What is the element at rank 9?"); System.out.println(l.get(9)); System.out.println("Removing head"); l.remove(); current = l.head; while (current != null) { System.out.print(current.element + " "); current = current.next; } System.out.println(); System.out.println("What is the element at rank 9?"); System.out.println(l.get(9)); } } class BadIndexException extends Exception { }