上一篇我们了解了哈希表与哈希冲突的基本概念,并且展示了一种哈希冲突的解决方法,今天我们来了解第二种哈希冲突的解决方法
开散列法,又叫链地址法
开散列法:首先对关键码集合用散列函数计算出散列地址,具有相同地址的关键码归于同一子集合,每一个子集合称为一个桶,各个桶中的元素通过一个无头结点的单链表连接起来,各链表的头结点存储在哈希表中,也就相当于,此时存储各个头结点的这个数组,是一个指针数组,这个数组里面存的是每一个单链表头结点指针
下面就是具体的代码实现
hash.h
#pragma once
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#define HASHMAXSIZE 1000
typedef int keytype;
typedef int valtype;
typedef int(*HashFunc)(keytype key);
typedef struct HashElem{
keytype key;
valtype value;
struct HashElem *next;
struct HashElem *pre;
}HashElem;
typedef struct HashTable{
HashElem* data[HASHMAXSIZE];
size_t size;
HashFunc func;
}HashTable;
void HashInit(HashTable *ht,HashFunc hash_func);
int HashFuncDefault(keytype key);
void HashInsert(HashTable *ht,keytype key,valtype value);
int HashFind(HashTable *ht,keytype key,valtype *value,HashElem **pre);
void HashRemove(HashTable *ht,keytype key);
void Hashdestroy(HashTable *ht);
hash.c
#include <stdio.h>
#include "hash.h"
//哈希桶
void HashInit(HashTabl