哈希表

/**
* 分别使用线性探测法和链地址法解决冲突
* 实现哈希表的插入、查找
**/
#include <iostream>
#include <algorithm>
#include <vector>

#define HASHSIZE 12

//单链表节点
struct NODE
{
    int key;
    NODE *next;
};
struct TableNode
{
    int addr;
    NODE *firstNode;
};
//使用链地址法解决冲突的哈希表结构
struct LinkHashTable
{
    TableNode table[HASHSIZE];
    int size;
};
//使用线性探测解决冲突的哈希表结构
struct HASHTABLE
{
    int table[HASHSIZE];
    int size;
};
void InitHash(HASHTABLE &hashtable)
{
    hashtable.size = HASHSIZE;
    for(int i = 0; i < HASHSIZE; ++i)
    {
        hashtable.table[i] = -1;
    }
}

//哈希函数
inline int Hash(int key)
{
    return key % HASHSIZE;
}

//插入,使用线性探测法解决冲突
void InsertHash(HASHTABLE &hashtable, int key)
{
    int addr = Hash(key);
    while(hashtable.table[addr] != -1)
    {
        addr = (addr + 1) % HASHSIZE;//线性探测
    }
    hashtable.table[addr] = key;
}

//查找key,成功返回1,失败返回0
int SearchHash(HASHTABLE &hashtable, int key)
{
    int addr = Hash(key);
    while(hashtable.table[addr] != key)
    {
        addr = (addr + 1) % HASHSIZE;
        if(hashtable.table[addr] == -1 || addr == Hash(key))
        {
            //如果遇到空槽或者循环回到了原点,则关键字不存在
            return 0;
        }        
    }
    return 1;
}


void InitLinkHash(LinkHashTable &LT)
{
    LT.size = HASHSIZE;
    for(int i = 0; i < HASHSIZE; ++i)
    {
        LT.table[i].addr = i;
        LT.table[i].firstNode = NULL;
    }
}
void InsertLinkHash(LinkHashTable &LT, int key)
{
    //采用头插法
    int addr = Hash(key);
    NODE *s = new NODE;
    s->key = key;
    s->next = LT.table[addr].firstNode;
    LT.table[addr].firstNode = s;
}

int SearchLinkHash(LinkHashTable &LT, int key)
{
    int addr = Hash(key);
    NODE *p = LT.table[addr].firstNode;
    while(p && p->key != key)
    {
        p = p->next;
    }
    if(!p)
    {
        return 0;
    }
    return 1;
}
int main(int nArgs, char* pArg[])
{
    int a[] = {12, 67, 56, 16, 25, 37, 22, 29, 15, 47, 48};
    int num = sizeof(a) / sizeof(a[0]);
    //使用线性探测法解决冲突
    HASHTABLE hashtable;
    InitHash(hashtable);    
    for(int i = 0; i < num; ++i)
    {
        InsertHash(hashtable, a[i]);
    }
    //进行查找
    std::cout << SearchHash(hashtable, 37) << std::endl;
    std::cout << SearchHash(hashtable, 7) << std::endl;

    //使用链地址法解决冲突
    LinkHashTable LT;
    InitLinkHash(LT);
    for(int i = 0; i < num; ++i)
    {
        InsertLinkHash(LT, a[i]);
    }

    std::cout << SearchLinkHash(LT, 25) << std::endl;
    std::cout << SearchLinkHash(LT, 7) << std::endl;

    system("pause");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值