// D. Scott // CCI - Problem 2.3 // Remove node from within a list given only access to that node class Node { Node next = null; int data; public Node(int d) { data = d; } void appendToTail(int d) { Node end = new Node(d); Node n = this; while (n.next != null) { n = n.next; } n.next = end; } } public static void main (String[] args) { // generate list Node list = new Node(19); Node head = list; list.appendToTail(5); list.appendToTail(8); list.appendToTail(143); list.appendToTail(2); list.appendToTail(12); list.appendToTail(36); list.appendToTail(14); list.appendToTail(99); list.appendToTail(7); // pluck a random node from list, say node 3 total = 0; node_num = 3; Node a_node_to_remove = list; System.out.println("The list:"); while (list != null) { total++; if (total == node_num) { a_node_to_remove = list; } System.out.println(total + ". " + list.data); list = list.next; } list = head; // now that we have a node, remove it without reference to // anything but that node: a_node_to_remove.data = a_node_to_remove.next.data; a_node_to_remove.next = a_node_to_remove.next.next; // print the list again: System.out.println("\nList with node " + node_num + " removed:"); count = 0; while (list != null) { count++; System.out.println(count + ". " + list.data); list = list.next; } }