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

来源:互联网 发布:java视频压缩技术 编辑:程序博客网 时间:2024/04/20 04:29

hashtable.h

#ifndef _HASHTABLE_H_#define _HASHTABLE_H_#define MinTableSize 100#define Prime 10007struct 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;}
0 0
原创粉丝点击