哈希表
//测试哈希表
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();
结果
123
-123
1056964608
536991770
上述这些代码是将符号位屏蔽得到非负数的整数然后再取余
哈希表相关方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure3
{
class HashST1<Key>
{
private LinkedList1<Key>[] hashtable;
private int N;
private int M;
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;
}
//添加元素方法
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);
}
}
}
若不在乎元素的顺序则使用哈希表,若在乎元素的顺序则使用红黑树
哈希表实现一个集合
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructure3
{
class HashST1Set<Key>:ISet<Key>
{
private HashST1<Key> hashST1;
public int Count => throw new NotImplementedException();
public bool IsEmpty => throw new NotImplementedException();
public HashST1Set(int M)
{
hashST1 = new HashST1<Key>(M);
}
public HashST1Set()
{
hashST1 = new HashST1<Key>();
}
public void Add(Key key)
{
hashST1.Add(key);
}
public void Remove(Key key)
{
hashST1.Remove(key);
}
public bool Contains(Key key)
{
return hashST1.Contains(key);
}
}
}
`