王道数据结构上查找一章有散列表的相关介绍,却没有提供对应代码,但是做题时有些题用散列表会很方便,在此提供散列表相关代码。
开放地址法几乎不会用到,它丧失了散列表最常大的优势,即通过散列函数寻找关键字位置,所以下面提供的是拉链法相关代码
数据结构
typedef struct LNode//链表节点
{
ElemType data;
struct LNode *next;
}LNode;
typedef struct HashTable//散列表
{
LNode *TheList[MaxSize];//指向LNode节点的指针数组
int TableSize;
}HashTable;
算法代码
void InitHash(HashTable *H, SeqList *L)
{
int p = L->len;
for (int i = 0; i < p; i++)
H->TheList[i] = NULL;
for (int i = 0, j; i < L->len; i++)
{
LNode *S;
j = L->data[i] % p; //j为元素对应的散列表数组单元
S = (LNode*)malloc(sizeof(LNode)); //创建同义词节点
S->data = i; //节点存储关键字下标
S->next = H->TheList[j]; //H->TheList[]相当于同义字链表的头指针
H->TheList[j] = S; //没有头节点的头插法
}
H->TableSize = p;
}
int Search_Hash(SeqList *L, ElemType key)
{
HashTable *H;
H = (HashTable *)malloc(sizeof(HashTable));
InitHash(H, L);
int p = L->len, i;
i = key % p;
LNode *S = H->TheList[i];
if (S == NULL)
return -1;//查找失败,返回-1
while (S != NULL)
{
if (L->data[S->data] == key)
return S->data;
else
S = S->next;
}
return -1;
}
测试程序
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int len;
}SeqList;
typedef struct LNode//链表节点
{
ElemType data;
struct LNode *next;
}LNode;
typedef struct HashTable
{
LNode *TheList[MaxSize];//指向LNode节点的指针数组
int TableSize;
}HashTable;
void InitHash(HashTable *H, SeqList *L);
int Search_Hash(SeqList *L, ElemType key);
void InitSeqList(SeqList *L, ElemType A[], int N);
void Print(SeqList *L);
int main()
{
SeqList *L;
L = (SeqList *)malloc(sizeof(SeqList));
ElemType A[MaxSize] = { 7,5,3,0,9,5,1,8,2 };
int N = 9;
InitSeqList(L,A, N);
Print(L);
for (int i = 1; i <= 9; i++)
{
printf("查找%d ", i);
int pos = Search_Hash(L, i);
if (pos == -1)
printf("表中没有此值\n");
else
printf("位置:%d\n", pos+1);
}
}
void InitHash(HashTable *H, SeqList *L)
{
int p = L->len;
for (int i = 0; i < p; i++)
H->TheList[i] = NULL;
for (int i = 0, j; i < L->len; i++)
{
LNode *S;
j = L->data[i] % p; //j为元素对应的散列表数组单元
S = (LNode*)malloc(sizeof(LNode)); //创建同义词节点
S->data = i; //节点存储关键字下标
S->next = H->TheList[j]; //H->TheList[]相当于同义字链表的头指针
H->TheList[j] = S; //没有头节点的头插法
}
H->TableSize = p;
}
int Search_Hash(SeqList *L, ElemType key)
{
HashTable *H;
H = (HashTable *)malloc(sizeof(HashTable));
InitHash(H, L);
int p = L->len, i;
i = key % p;
LNode *S = H->TheList[i];
if (S == NULL)
return -1;//查找失败,返回-1
while (S != NULL)
{
if (L->data[S->data] == key)
return S->data;
else
S = S->next;
}
return -1;
}
void InitSeqList(SeqList *L, ElemType A[], int N)
{
for (int i = 0; i < N; i++)
L->data[i] = A[i];
L->len = N;
}
void Print(SeqList *L)
{
for (int i = 0; i < L->len; i++)
printf("%d ", L->data[i]);
printf("\n");
}
运行结果