哈希表
哈希表-1
数据结构与算法分析,P631习题9.设计一个ADT HashTable类模板。基本操作至少包括构造函数、析构函数、复制构造函数、在散列表中查找项以及需哦那个散列表中删除一个项。使用随机散列函数和建链策略来处理冲突。
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <vector>
#include <list>
#include <algorithm>
template <typename ElementType>
class HashTable
{
public:
HashTable(int n=0);
HashTable(const HashTable & original);
~HashTable();
void insert(ElementType item,int key);
int search(ElementType item,int key);
void display(ostream & out);
private:
vecotr<list<ElementType>> myTable;
unsigned hash(int key); //Hasn function
};
template <typename ElementType>
inline HashTable<ElementType>::HashTable(int n)
{
list<ElementType> emptyList;
for(int i=1;i<=n;i++)
myTable.push_back(emptyList);
}
template <typename ElementType>
inline HashTable<ElementType>::HashTable(const HashTable<ElementType> & original)
{
myTable = original.myTable; //??????????为什么这样就够了,不需要复制吗
//难道是因为myTable和original本身的类型(vector<list>)已经有复制构造函数,我们不用自己写了
}
template <typename ElementType>
inline HashTable<ElementType>::~HashTable()
{} //vector and list destructors take care of this
template <typename ElementType>
inline void HashTable<ElementType>::insert(ElementType item,int key)
{
if(search(item,key)<0)
myTable[hash(key)].push_front(item);
else
cerr<<item<<" already in table.\n";
}
template<typename ELementType>
int HashTable<ElelementType>::search(ElementType item,int key)
{
int loc=hash(key);
if(find(myTable[loc].begin(),myTable[loc].end(),item)!=myTable[loc].end()) //利用myTable是list这个特点,直接用list的函数find
return loc;
else
return -1;
}
template <typename ElementType>
void HashTable<ElementType>::display(ostream & out)
{
for(int i=0;i<myTable.size();i++) //利用myTable是list这个特点,直接用list的函数size()。
{
out<<setw(2)<<i<<": ";
list<ELementType>::iterator it; //利用myTable是list这个特点,直接用迭代器做。
for(it=myTble[i].begin;it!=myTable[i].end();it++)
out<<*it<<" ";
out<<endl;
}
}
template<typename ElementType>
inline unsigned HashTable<ELementType>::hash(int number)
{
const unsigned;
MULTIPLER = 25173U,ADDEND = 13829U,MODULUS = 65536U;
unsinged x=(MULTIPLIER*number+ADDEND)%MODULUS%myTable.size(); //书上P630随机散列的中的大随机数
return x;
}