|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +/** |
| 4 | + * Implement a hash table |
| 5 | + * |
| 6 | + * Tags: DS |
| 7 | + */ |
| 8 | +public class MyHashtable { |
| 9 | + |
| 10 | + LinkedList<Node>[] array; |
| 11 | + int size; |
| 12 | + |
| 13 | + class Node { |
| 14 | + String key; |
| 15 | + Object value; |
| 16 | + |
| 17 | + public Node(String k, Object v) { |
| 18 | + key = k; |
| 19 | + value = v; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + public MyHashtable(int size) { |
| 24 | + array = new LinkedList[size]; |
| 25 | + this.size = size; |
| 26 | + } |
| 27 | + |
| 28 | + public static void main(String[] args) { |
| 29 | + |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Create a new linkedlist if not in array, add value and set the list |
| 34 | + * If linkedlist in array, search for the key and update value |
| 35 | + * If key not found, add a new node with value to the end of list |
| 36 | + */ |
| 37 | + public void put(String key, Object value) { |
| 38 | + if (key == null || value == null) throw new IllegalArgumentException(); |
| 39 | + int index = hashcode(key) % size; |
| 40 | + if (array[index] == null) { |
| 41 | + LinkedList<Node> list = new LinkedList<Node>(); |
| 42 | + list.add(new Node(key, value)); |
| 43 | + array[index] = list; |
| 44 | + } else { |
| 45 | + LinkedList<Node> list = array[index]; |
| 46 | + boolean found = false; |
| 47 | + for (Node n : list) { |
| 48 | + if (n.key.equals(key)) { |
| 49 | + n.value = value; |
| 50 | + found = true; |
| 51 | + break; |
| 52 | + } |
| 53 | + } |
| 54 | + if (!found) list.add(new Node(key, value)); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * If not in array, return null |
| 60 | + * If in array, get the linkedlist and search for the key |
| 61 | + * If no key, return null |
| 62 | + */ |
| 63 | + public Object get(String key) { |
| 64 | + if (key == null) return null; // validation |
| 65 | + int index = hashcode(key) % size; |
| 66 | + if (array[index] == null) return null; |
| 67 | + LinkedList<Node> list = array[index]; |
| 68 | + for (Node n : list) { |
| 69 | + if (key.equals(n.key)) { |
| 70 | + return n.value; |
| 71 | + } |
| 72 | + } |
| 73 | + return null; |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * hash function to get the index |
| 78 | + */ |
| 79 | + private int hashcode(String key) { |
| 80 | + // TODO implement hash function |
| 81 | + return 0; |
| 82 | + } |
| 83 | +} |
0 commit comments