您的位置:首页 > 其它

算法导论11.2散列表Hash tables链式法解决碰撞11.3.1除法散列法

2015-02-12 12:53 281 查看




11.2是第11章的主要内容,11章叫散列表(HashTables)11.2也叫散列表(HashTables)

11.3节讲散列函数(比如除尘散列法),11.4节讲处理碰撞的另外一种方法区别于链式法技术

散列技术,有两个事情要做,一是先哈希函数(11.3),二是解决碰撞技术(11.2链式解决碰撞,11.4开放寻址解决碰撞)。

















/*
*IA_11.2ChainedHash.h
*
*Createdon:Feb13,2015
*Author:sunyj
*/

#ifndefIA_11_2CHAINEDHASH_H_
#defineIA_11_2CHAINEDHASH_H_

#include<iostream>
#include<string.h>

#include"IA_10.2LinkedLists.h"

//CHAINED-HASH-INSERT(T,x)
//insertxattheheadoflistT[h(x.key)]

//CHAINED-HASH-SEARCH(T,k)
//searchforanelementwithkeykinlistT[h(k)]

//CHAINED-HASH-DELETE(T,x)
//deletexfromthelistT[h(x.key)]

template<classT>classChainedHashTable{
public:
ChainedHashTable(int64_tconstn):size(n)
{
data=newLinkedList<int64_t,T>
();
}
~ChainedHashTable(){}
int64_tHashFunc(int64_tconstkey)
{
returnkey%size;
}
Node<int64_t,T>*search(int64_tconstkey)
{
returndata[HashFunc(key)].search(key);
}
//theuserofthisclass,hastoinvokesearchfirst
//thisinterfaceassumethatxwasnotinthehashtable
voidinsert(Node<int64_t,T>*x)
{
(data[HashFunc(x->key)]).insert(x);
}
voiddel(Node<int64_t,T>*x)
{
data[HashFunc(x->key)].del(x);
}
voidprint(int64_tkey)
{
data[HashFunc(key)].print();
}
private:
LinkedList<int64_t,T>*data;
int64_tconstsize;
};

#endif/*IA_11_2CHAINEDHASH_H_*/


/*
*IA_11.2ChainedHash.cpp
*
*Createdon:Feb12,2015
*Author:sunyj
*/

#include"IA_11.2ChainedHash.h"

intmain()
{
/*
*Aprimenottooclosetoanexactpowerof2isoftenagoodchoiceform.For
example,supposewewishtoallocateahashtable,withcollisionsresolvedby
chaining,toholdroughlyn=2000characterstrings,whereacharacterhas8bits.
Wedon'tmindexamininganaverageof3elementsinanunsuccessfulsearch,and
soweallocateahashtableofsizem=701.Wecouldchoose701because
itisaprimenear2000=3butnotnearanypowerof2.
*/
ChainedHashTable<int64_t>table(701);//Thedivisionmethod,

Node<int64_t,int64_t>node1(1,100);
Node<int64_t,int64_t>node4(4,400);
Node<int64_t,int64_t>node16(16,1600);
Node<int64_t,int64_t>node9(9,900);
if(nullptr==table.search(node1.key))
{ //searchbeforeinsert
table.insert(&node1);
}
else
{
std::cout<<"node1alreadyexist"<<std::endl;
}
if(nullptr==table.search(node1.key))
{
table.insert(&node1);
}
else
{
std::cout<<"node1alreadyexist"<<std::endl;
}
table.insert(&node4);
table.insert(&node16);
table.insert(&node9);
table.print(4);
Node<int64_t,int64_t>node25(25,2500);
table.insert(&node25);
table.print(16);
//searchbeforedel,oryouareclearlysurethat,therearethisnodeexist.
//ifnode1isnotexist,andyouinvokedel,programwillcrush
table.del(&node1);
table.print(9);
Node<int64_t,int64_t>*tmp;
tmp=table.search(9);
table.del(tmp);
table.print(9);
return0;
}










内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: