C# creating a hash table linked list
class Program
{
public class MyHashTable
{
public Node[] universe;
public readonly int tableSize;
public MyHashTable(int maxTableSize)
{
tableSize = maxTableSize;
universe = new Node[tableSize];
}
public class Node
{
public int Key { get; set; }
public object Value { get; set; }
public Node Next { get; set; }
public Node Previous { get; set; }
}
private int HashFuncation(int key)
{
int index = 7;
int asciiVal = 0;
for (int i = 0; i < key; i++)
{
asciiVal = (int)key * i;
index = index * 31 + asciiVal;
}
return index % tableSize;
}
public void Insert(int key, object value)
{
int genIndex = HashFuncation(key);
Node node = universe[genIndex];
if (node == null)
{
universe[genIndex] = new Node() { Key = key, Value = value };
return;
}
if (node.Key == key)
throw new Exception("Can't use same key!");
while (node.Next != null)
{
node = node.Next;
if (node.Key == key)
throw new Exception("Can't use same key!");
}
Node newNode = new Node() { Key = key, Value = value, Previous = node, Next = null };
node.Next = newNode;
}
public object GetnthValue(int key)
{
int genIndex = HashFuncation(key);
Node node = universe[genIndex];
while (node != null)
{
if (node.Key == key)
{
return node.Value;
}
node = node.Next;
}
throw new Exception("Don't have the key in hash!");
}
}
static void Main(string[] args)
{
MyHashTable hashTable = new MyHashTable(50);
hashTable.Insert(1, 5);
hashTable.Insert(2, 6);
hashTable.Insert(3, 7);
hashTable.Insert(4, 8);
Console.WriteLine("hash table");
Console.WriteLine("1,5 -> 2,6 -> 3,7 -> 4,8");
Console.WriteLine("Value of the nth node is: " + hashTable.GetnthValue(1));
Console.ReadLine();
}
}