C++ 拉链法解决哈希表冲突

将所有哈希函数结果相同的节点连接在同一个单链表中。

#include <string>
#include<stdio.h>
#include<vector>
struct ListNode
{
 int val;
 ListNode* next;
 ListNode(int x) : val(x), next(NULL) {}
};
int int_func(int val, int table_len)
{
 return val % table_len;
}
void insert(ListNode* hash_table[], ListNode* node, int table_len)
{
 int hash_key = int_func(node->val, table_len);
 node->next = hash_table[hash_key];
 hash_table[hash_key] = node;
}
bool search(ListNode * hash_table[], int value, int table_len)
{
 int hash_key = int_func(value, table_len);
 ListNode* head = hash_table[hash_key];
 while (head)
 {
  if (head->val==value)
  {
   return true;
  }
  head = head->next;
 }
 return false;
}
int main()
{
 const int TABLE_LEN = 11;
 ListNode* hash_table[TABLE_LEN] = {0};
 std::vector<ListNode*> hash_node_vec;
 int test[8] = {1,1,4,9,20,30,150,500};
 for (int i = 0; i < sizeof(test)/sizeof(test[0]); i++)
 {
  hash_node_vec.push_back(new ListNode(test[i]));
 }
 for (int i = 0; i < hash_node_vec.size(); i++)
 {
  insert(hash_table, hash_node_vec[i], TABLE_LEN);
 }
 printf("Hash table:\n");
 for (int  i = 0; i < TABLE_LEN; i++)
 {
  printf("[%d]:",i);
  ListNode* head = hash_table[i];
  while (head)
  {
   printf("->%d", head->val);
   head = head->next;
  }
  printf("\n");
 }
 printf("\n");
 printf("Test search: \n");
 for (int i = 0; i < 10; i++)
 {
  if (search(hash_table,i, TABLE_LEN))
  {
   printf("%d is in the hash table. \n",i);
  }
  else
  {
   printf("%d is not in the hash table.\n", i);
  }
 }
 return 0;
}

运行结果为:

Hash table:
[0]:
[1]:->1->1
[2]:
[3]:
[4]:->4
[5]:->500
[6]:
[7]:->150
[8]:->30
[9]:->20->9
[10]:

Test search:
0 is not in the hash table.
1 is in the hash table.
2 is not in the hash table.
3 is not in the hash table.
4 is in the hash table.
5 is not in the hash table.
6 is not in the hash table.
7 is not in the hash table.
8 is not in the hash table.
9 is in the hash table.
发布了79 篇原创文章 · 获赞 62 · 访问量 2200

猜你喜欢

转载自blog.csdn.net/weixin_44208324/article/details/105008981