Pastebin launched a little side project called HostCabi.net, check it out ;-)Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 28th, 2012  |  syntax: None  |  size: 1.55 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to hash generic key in generic hash table implementation?
  2. class Node<T, U>
  3. {
  4.     public T key;
  5.     public U value;
  6.     public Node<T, U> next;
  7.     public Node(T key, U value, Node<T, U> next)
  8.     {
  9.         this.key = key;
  10.         this.value = value;
  11.         this.next = next;
  12.     }
  13.  }
  14.  
  15. public  class HashTable<T,U>
  16. {
  17.     int length;
  18.     Node<T,U>[] buckets;
  19.     public HashTable(int length)
  20.     {
  21.         this.length = length;
  22.         buckets = new Node<T,U>[length];
  23.     }
  24.  
  25.     public void Display()
  26.     {
  27.         for (int bucket = 0; bucket<buckets.Length; bucket++)
  28.         {
  29.             Node<T,U> current = buckets[bucket];
  30.             Console.Write(bucket + ":");
  31.             while (current != null)
  32.             {
  33.                 Console.Write("["+current.key+","+current.value+"]");
  34.                 current=current.next;
  35.             }
  36.             Console.WriteLine();
  37.         }
  38.     }
  39.      //  private int Hash(T Tkey) ...
  40.     //// non-generic version of hash function
  41.  
  42.     private int Hash(string str)
  43.     {
  44.         int h=0;
  45.         foreach(var s in str)
  46.             h=127*h+s;
  47.         return h%length;
  48.  
  49.     }
  50.      ////
  51.     public void Insert(T key, U value)
  52.     {
  53.         int bucket = Hash(key);
  54.         buckets[bucket] = new Node<T,U>(key, value, buckets[bucket]);
  55.     }
  56.     public U Search(T key)
  57.     {
  58.         Node<T,U> current = buckets[Hash(key)];
  59.         while (current != null)
  60.         {
  61.             if (current.key.Equals(key))
  62.                 return current.value;
  63.             current= current.next;
  64.         }
  65.         throw new Exception(key+ "Not found");
  66.     }