-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSeparateChainingHashTable.cs
More file actions
56 lines (40 loc) · 1.63 KB
/
SeparateChainingHashTable.cs
File metadata and controls
56 lines (40 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Collections.Generic;
using System.Linq;
namespace AlgorithmsAndDataStructures.DataStructures.HashTable;
public class SeparateChainingHashTable<TKey, TValue>
{
private readonly LinkedList<HashEntry<TKey, TValue>>[] hashTable;
public SeparateChainingHashTable(int hashTableSize = 8)
{
hashTable = new LinkedList<HashEntry<TKey, TValue>>[hashTableSize];
}
public void Add(TKey key, TValue value)
{
var hash = Math.Abs(key.GetHashCode() % hashTable.Length);
hashTable[hash] ??= new LinkedList<HashEntry<TKey, TValue>>();
var entry = hashTable[hash]?.FirstOrDefault(arg => arg.Key?.Equals(key) == true);
if (entry != null)
entry.Value = value;
else
hashTable[hash].AddLast(new HashEntry<TKey, TValue> { Value = value, Key = key });
}
public bool Find(TKey key)
{
var hash = Math.Abs(key.GetHashCode() % hashTable.Length);
return hashTable[hash]?.FirstOrDefault(arg => arg.Key?.Equals(key) == true) != null;
}
public TValue Get(TKey key)
{
var hash = Math.Abs(key.GetHashCode() % hashTable.Length);
var entry = hashTable[hash]?.FirstOrDefault(arg => arg.Key?.Equals(key) == true);
if (entry is null) throw new ArgumentException($"Hash table contains no entry with key {key}");
return entry.Value;
}
public void Delete(TKey key)
{
var hash = Math.Abs(key.GetHashCode() % hashTable.Length);
var entry = hashTable[hash]?.FirstOrDefault(arg => arg.Key?.Equals(key) == true);
if (entry != null) hashTable[hash].Remove(entry);
}
}