133-哈希表-线性探测法代码实现

1、哈希表-线性探测法理论

在这里插入图片描述
线性探测法的理论我们在上一篇博客已经阐述了。

现在我们来看看线性探测法的增删查的代码思想:

1.1、哈希表的增加元素

在这里插入图片描述
注意:

  • 往后遍历寻找空闲位置的时候,要注意是环形遍历哦!不然访问数组就越界了。
  • 在添加元素,发生位置被占用,即发生哈希冲突后,在向后遍历寻找空闲位置的时候,我们要知道,这个空闲的位置是有两种情况的:
    • 1、这个位置一直是空的,没放过元素
    • 2、这个位置是空的,以前放过元素,后来被删除了

1.2、哈希表的查询操作

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
线性探测法哈希表中的一种解决哈希冲突的方法。当哈希函数将两个不同的键映射到了同一个位置时,就会发生哈希冲突。线性探测法就是在这种情况下,顺序地检查下一个位置,直到找到一个空位置或者找遍整个哈希表为止。 以下是使用线性探测法创建人名哈希表代码示例: ```c++ #include <iostream> #include <string> using namespace std; const int TABLE_SIZE = 10; class Person { public: string name; int age; Person(string n, int a) { name = n; age = a; } }; class HashTable { private: Person* table[TABLE_SIZE]; public: HashTable() { for (int i = 0; i < TABLE_SIZE; i++) { table[i] = nullptr; } } int hash(string key) { int hashVal = 0; for (int i = 0; i < key.length(); i++) { hashVal += key[i]; } return hashVal % TABLE_SIZE; } void insert(Person* p) { int index = hash(p->name); while (table[index] != nullptr) { index++; index %= TABLE_SIZE; } table[index] = p; } Person* search(string name) { int index = hash(name); while (table[index] != nullptr && table[index]->name != name) { index++; index %= TABLE_SIZE; } if (table[index] == nullptr) { return nullptr; } else { return table[index]; } } void remove(string name) { int index = hash(name); while (table[index] != nullptr && table[index]->name != name) { index++; index %= TABLE_SIZE; } if (table[index] != nullptr) { delete table[index]; table[index] = nullptr; } } void printTable() { for (int i = 0; i < TABLE_SIZE; i++) { if (table[i] != nullptr) { cout << "Index " << i << ": " << table[i]->name << endl; } else { cout << "Index " << i << ": Empty" << endl; } } } }; int main() { HashTable h; Person* p1 = new Person("Alice", 25); Person* p2 = new Person("Bob", 30); Person* p3 = new Person("Charlie", 35); Person* p4 = new Person("David", 40); h.insert(p1); h.insert(p2); h.insert(p3); h.insert(p4); h.printTable(); Person* p = h.search("Bob"); if (p != nullptr) { cout << "Bob is " << p->age << " years old." << endl; } else { cout << "Bob not found." << endl; } h.remove("Bob"); h.printTable(); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liufeng2023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值