散列是一种用于以常数平均时间执行插入、删除和查找的技术。理想的散列数据结构只不过是一个包含有关键字的具有固定大小的数组。典型情况下,一个关键字就是一个
带有相关值(工资信息等)的字符串。
散列函数主要的问题就是解决冲突的消除问题。如果当一个元素被插入时另一个元素已经存在(散列值存在),那么就会产生冲突。解决这种冲突的方法有几种,一般用最
简单的两种:分离链接法、开放地址法
1.分离链接法
//分离链接散列表的头文件声明
#ifndef HASH_H_INCLUDED
#define HASH_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
typedef unsigned int Index;
typedef int DataType;
struct ListNode;
typedef struct ListNode *Position;
typedef Position List;
struct HashTbl;
typedef struct HashTbl *HashTable;
HashTable Hash_InitTable(int TableSize);
void Hash_Insert(DataType key, HashTable H);
void Hash_Delete(DataType key, HashTable H);
void Hash_Show(HashTable H);
int Hash_Free(HashTable H);
#endif // HASH_H_INCLUDED
//分离链接散列表的功能函数声明
#include "hash.h"
struct ListNode
{
DataType Data;
Position Next;
};
struct HashTbl
{
int TableSize;
List *TheLists;
};
void Print_Err(char *str);
int NextPrime(int n);
Index Hash(const int key, int tablesize)
{
unsigned int hashval = 0;
int x;
x = key;
if(x < 0)
{
printf("the key is low 0\n");
exit(-1);
}
while(x != 0)
{
hashval = (hashval << 3) + x%10;
x /= 10;
}
return hashval % tablesize;
}
HashTable Hash_InitTable(int Size)
{
HashTable H;
int i;
H = (HashTable)malloc(sizeof(struct HashTbl));
if(H == NULL)
Print_Err("no space for malloc H");
H->TableSize = NextPrime(Size);
H->TheLists = (List *)malloc(sizeof(List) * H->TableSize);
if(H->TheLists == NULL)
Print_Err("no space for malloc H->TabLists");
for(i = 0; i < H->TableSize; i++)
{