Hash Table,叫做哈希表,也叫做散列表。
概念:通过某种对应关系h,使得每一个元素和储存位置一一对应。这种对应关系称为哈希函数。它最大的优点就是插入、搜索和删除得很快(O(1))。
碰撞(Collision):不同的关键字对应同一个哈希地址
本文主要介绍的是解决碰撞的方法之一:chaining
原理:
In chainning,wo palce all the elements that hash to the same plot into the same list.
如果不同的key通过hash function得到的相同结果,那么就将他们放在同一个list中。如下图:
操作:
1.查找:
先找到key的索引:index=hashFunction(key)
然后遍历这个链表:
// get the hash index of key
int index = hashFunction(key);
// find the key in (inex)th list
list <int> :: iterator i;
for (i = table[index].begin();
i != table[index].end(); i++) {
if (*i == key)
break;
}
2.插入:
void Ha