1.哈希函数的设计
class Program
{
static void Main(string[] args)
{
int a = 123;
Console.WriteLine(a.GetHashCode());
int b = -123;
Console.WriteLine(b.GetHashCode());
float c = 0.5f;
Console.WriteLine(c.GetHashCode());
string d = "abc";
Console.WriteLine(d.GetHashCode());
Console.Read();
}
}
2.哈希冲突处理
基于拉链法的顺序查找哈希表:
class HashST1<Key>
{
private LinkedList1<Key>[] hashtable; //每个位置都指向一条链表,将冲突的元素都存在链表中
private int M;
private int N;
public HashST1(int M)
{
this.M = M;
N = 0;
hashtable = new LinkedList1<Key>[M];
for (int i = 0; i < M; i++)
hashtable[i] = new LinkedList1<Key>();
}
public HashST1() : this(97) { }
public int Count { get { return N; } }
public bool IsEmpty { get { return N == 0; } }
//将键转化为数组的索引
private int Hash(Key key)
{
return (key.GetHashCode() & 0x7fffffff) % M;
}
}
3.哈希表添加、删除、包含
public void Add(Key key)
{
LinkedList1<Key> list = hashtable[Hash(key)];
if (list.Contains(key))
return;
else
{
list.AddFirst(key);
N++;
}
}
public void Remove(Key key)
{
LinkedList1<Key> list = hashtable[Hash(key)];
if (list.Contains(key))
{
list.Remove(key);
N--;
}
}
public bool Contains(Key key)
{
LinkedList1<Key> list = hashtable[Hash(key)];
return list.Contains(key);
}