/** * Date: Feb 02, 06 * Course: cs601 * Class name: LinkedListDictionary.java * Purpose: implements the Dictionary interface */ package dict; public class LinkedListDictionary implements Dictionary{ public ListItem head; public LinkedListDictionary () { head = null; } public void map(String key, Object o) { if (key == "" || o == "") { System.out.println("Null cannot be added!!!"); System.exit(0); } Object a = key+":"+o; ListItem l = new ListItem(a); //if the list is empty if (head==null) { head = l; } else // add to end { ListItem walker = head; while (walker.next!= null) { walker=walker.next; } walker.next = l; } } public Object unlink (String key) { ListItem walker = head; String buffer = ""; String [] splits; String a = (String)walker.data; splits = a.split(":"); //if there's only one object in the list if (splits[0].compareTo(key) == 0){ head = head.next; return walker.data; } //to remove the second object if (walker.next != null) { String b = (String)walker.next.data; String [] splitss = b.split(":"); if (splitss[0].compareTo(key) == 0) { Object rval = walker.next.data; walker.next = walker.next.next; return rval; } } //loop through the rest of the list while (walker.next.next!= null && !(splits[0].compareTo(key) == 0)) { walker = walker.next; a = (String)walker.next.data; splits = a.split(":"); } if (splits[0].compareTo(key) == 0){ Object rval = walker.next.data; walker.next = walker.next.next; return rval; } if (buffer == "") { return "null " + null; } else return "buffer " + buffer; } public Object find (String key) { ListItem walker = head; String buffer = ""; while (walker!= null) { String [] splits; String a = (String)walker.data; splits = a.split(":"); if (splits[0].compareTo(key) == 0){ buffer += walker.data + " "; } walker = walker.next; } if (buffer == "") { return null; } else return buffer; } public String toString () { ListItem walker = head; String buffer = ""; buffer += "["; while (walker!= null){ buffer += walker.data; if (walker.next != null) buffer += ","; walker=walker.next; } buffer += "]"; return buffer; } /* public static void main(String args[]){ LinkedListDictionary list = new LinkedListDictionary(); list.map("aaa","ABC"); list.map("bbb","DEF"); list.map("ccc","GHI"); list.map("ddd","JKL"); System.out.println("find " + list.find("w") ); System.out.println("find " + list.find("aaa") ); System.out.println("unlink " + list.unlink("ccs") ); System.out.println(list); }*/ }