} // End Put // Find a value using a key public int GetValue(string key) { HEntry[] temp = table; int h = Math.Abs(key.GetHashCode() % tableSize); // If there is no such key if (temp[h] == null) { return(0); } else // Else { HEntry entry = temp[h]; // Hold slot while (entry != null && !entry.key.Equals(key)) // Find matching key { entry = entry.next; } if (entry == null) // Key wasn't found { return(0); } else // Key was found { return(entry.value); } } } // End GetVal
// Add a value to the hash table public void Put(string key, int value) { // Check if we should expand if (count > (int)tableSize * .5) { this.ExpandCapacity(); } // Hash string int h = Math.Abs(key.GetHashCode() % tableSize); // Create new entry HEntry entry = new HEntry(key, value); // Insert entry to table array if (table[h] == null) { // No collision, insert entry table[h] = entry; ++count; } else { // Detected collision, step through list HEntry current = table[h]; while (current.next != null) { // Check keys for match if (current.key.Equals(entry.key)) { // Increment value current.value++; return; } current = current.next; } // Next is null, insert node current.next = entry; ++count; } } // End Put
// Entry constructor public HEntry(string key, int value) { this.key = key; this.value = value; this.next = null; }