Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- How to hash generic key in generic hash table implementation?
- class Node<T, U>
- {
- public T key;
- public U value;
- public Node<T, U> next;
- public Node(T key, U value, Node<T, U> next)
- {
- this.key = key;
- this.value = value;
- this.next = next;
- }
- }
- public class HashTable<T,U>
- {
- int length;
- Node<T,U>[] buckets;
- public HashTable(int length)
- {
- this.length = length;
- buckets = new Node<T,U>[length];
- }
- public void Display()
- {
- for (int bucket = 0; bucket<buckets.Length; bucket++)
- {
- Node<T,U> current = buckets[bucket];
- Console.Write(bucket + ":");
- while (current != null)
- {
- Console.Write("["+current.key+","+current.value+"]");
- current=current.next;
- }
- Console.WriteLine();
- }
- }
- // private int Hash(T Tkey) ...
- //// non-generic version of hash function
- private int Hash(string str)
- {
- int h=0;
- foreach(var s in str)
- h=127*h+s;
- return h%length;
- }
- ////
- public void Insert(T key, U value)
- {
- int bucket = Hash(key);
- buckets[bucket] = new Node<T,U>(key, value, buckets[bucket]);
- }
- public U Search(T key)
- {
- Node<T,U> current = buckets[Hash(key)];
- while (current != null)
- {
- if (current.key.Equals(key))
- return current.value;
- current= current.next;
- }
- throw new Exception(key+ "Not found");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement