class List { int key; int value; List next; } public class Lookup { public static void main(String[] args) { if ( args.length < 1 ) { System.out.println("Usage: java Lookup KEY\n"); System.exit(1); } List head = makeList(); System.out.print("List: "); Print( head ); int searchKey = Integer.parseInt( args[0] ); System.out.println("Look up: " + searchKey); int searchValue = Lookup( head, searchKey); System.out.println("Returned value = " + searchValue); } /* ============================================= Recursive look up function ============================================= */ static int Lookup( List h, int searchKey ) { if ( h == null ) return 0; // Not found is represented by 0 else if ( h.key == searchKey ) return (h.value); else return Lookup( h.next, searchKey ); } // Help function: print list public static void Print(List head) { while (head != null) { System.out.print("[" + head.key + "," + head.value + "]"); head = head.next; if ( head != null ) System.out.print("->"); } System.out.println(); } // Help function: make the list in teaching notes public static List makeList() { int[] key = {111, 222, 333, 444, 555}; int[] value = {58, 67, 34, 87, 98}; List h = null; List p; for (int i = key.length-1; i >= 0; i-- ) { p = new List( ); p.key = key[i]; p.value = value[i]; p.next = h; h = p; } return h; } }