C++ 链式哈希程序

17 Mar 2025 | 5 分钟阅读

哈希表链表法究竟是什么?

链表法是一种哈希表冲突避免技术。

当哈希表中的两个键哈希到同一个索引时,就会发生冲突。冲突是一个问题,因为哈希表中的每个槽位只应该容纳一个元素。

C++ hashing programme with chaining

链表法

链表法中的哈希表是一个链表数组,每个索引都有自己的链表。

所有映射到相同索引的键值对都将存储在该索引的链表中。

链表法的优点

  • 通过链表法,哈希表中的插入始终以 O(1) 的时间复杂度进行,因为链表允许在常数时间内插入。
  • 只要有足够的空间,链式哈希表理论上可以无限增长。
  • 链式哈希表永远不需要调整大小。

链表法的实现

让我们编写一个哈希函数,以确保我们的哈希表有 'N' 个桶。

要将节点添加到哈希表,我们必须首先确定给定键的哈希索引。它也可以使用哈希函数计算。

示例:哈希索引 = 键 % 桶数

插入: 移动到与上面计算的哈希索引对应的桶,并将新节点插入到列表的末尾。

删除: 要从哈希表中删除一个节点,计算键的哈希索引,移动到与计算的哈希索引对应的桶,在当前桶中的列表中搜索具有给定键的节点,并将其删除(如果找到)。

算法

对于插入

对于删除

对于搜索

编码

输出

1. Insert element into the table
2. Search element from the key
3. Delete element at a key
4. Exit
Enter your choice: 1
Enter element to be inserted: 2
Enter key at which element to be inserted: 1
1. Insert element into the table
2. Search element from the key
3. Delete element at a key
4. Exit
Enter your choice: 1
Enter element to be inserted: 3
Enter key at which element to be inserted: 4
1. Insert element into the table
2. Search element from the key
3. Delete element at a key
4. Exit
Enter your choice: 1
Enter element to be inserted: 7
Enter key at which element to be inserted: 6
1. Insert element into the table
2. Search element from the key
3. Delete element at a key
4. Exit
Enter your choice: 1
Enter element to be inserted: 8
Enter key at which element to be inserted: 9
1. Insert element into the table
2. Search element from the key
3. Delete element at a key
4. Exit
Enter your choice: 2
Enter key of the element to be searched: 6
Element found at key 6: 7
1. Insert element into the table
2. Search element from the key
3. Delete element at a key
4. Exit
Enter your choice: 2
Enter key of the element to be searched: 7
No Element found at key 7
1. Insert element into the table
2. Search element from the key
3. Delete element at a key
4. Exit
Enter your choice: 3
Enter key of the element to be deleted: 9
Element Deleted
1. Insert element into the table
2. Search element from the key
3. Delete element at a key
4. ExitC
Enter your choice: 4

时间复杂度

  • 搜索: O (1+(n/m))
  • 删除: O (1+(n/m))
  • 其中 n = 哈希表中的槽位数量
    m = 要插入的键的数量
    这里的 n/m 是负载因子。
  • 负载因子必须尽可能小。