哈希表

哈希表

哈希表-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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值