您的位置:首页 > 编程语言 > C语言/C++

分离链接散列表--C语言实现

2015-12-30 18:07 471 查看
hashtable.h

#ifndef _HASHTABLE_H_
#define _HASHTABLE_H_
#define MinTableSize 100
#define Prime 10007

struct ListNode;
typedef struct ListNode* Position;
struct HashTbl;
typedef struct HashTbl* HashTable;
typedef int ElementType;
typedef Position List;

HashTable InitializeTable(int TableSize);
void DestroyTable(HashTable H);
Position Find(ElementType Key, HashTable H);
void Insert(ElementType Key, HashTable H);
ElementType Retrieve(Position P);

#endif


hashtable.c

#include<stdio.h>
#include<stdlib.h>
#include"hashtable.h"

struct ListNode
{
ElementType Element;
Position Next;
};
struct HashTbl
{
int TableSize;
List* TheLists;
};

int Hash(ElementType Key,int TableSize)
{
return Key%TableSize;//简化问题,把Key当做数字处理
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
int i;
if (TableSize < MinTableSize)
{
printf("ERROR!\n");
return NULL;
}
H = (HashTable)malloc(sizeof(struct HashTbl));
if (H == NULL)
{
printf("FAILURE!\n");
exit(EXIT_FAILURE);
}
H->TableSize = Prime;//Prime 最好是一个根据TableSize变化的质数。
H->TheLists = (List *)malloc(sizeof(List)*H->TableSize);
if (H->TheLists == NULL)
{
printf("FAILURE!\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < H->TableSize;i++)
{
H->TheLists[i] = (List)malloc(sizeof(struct ListNode));
if (H->TheLists[i] == NULL)
{
printf("FAILURE!\n");
exit(EXIT_FAILURE);
}
else
H->TheLists[i]->Next = NULL;
}
return H;
}
void DestroyTable(HashTable H)
{
for (int i = 0; i < H->TableSize; i++)
{
Position temp=H->TheLists[i]->Next;
H->TheLists[i]->Next = NULL;
while (temp != NULL)
{
Position t = temp->Next;
free(temp);
temp = t;
}
}
}
Position Find(ElementType Key, HashTable H)
{
Position P;
List L;
L = H->TheLists[Hash(Key, H->TableSize)];
P = L->Next;
while (P != NULL && P->Element != Key)
P = P->Next;
return P;
}
void Insert(ElementType Key, HashTable H)
{
Position Pos, NewCell;
List L;
Pos = Find(Key, H);
if (Pos == NULL)
{
NewCell = (Position)malloc(sizeof(struct ListNode));
if (NewCell == NULL)
{
printf("FAILURE!\n");
exit(EXIT_FAILURE);
}
else
{
L = H->TheLists[Hash(Key, H->TableSize)];
NewCell->Element = Key;
NewCell->Next = L->Next;
L->Next = NewCell;
}
}
}
ElementType Retrieve(Position P)
{
if(!P)
return P->Element;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  散列 hash