开放定址散列表--C语言实现

来源:互联网 发布:excel数据有效性在哪 编辑:程序博客网 时间:2024/05/21 14:55

hashtable.h

#ifndef _HASHTABLE_H_#define _HASHTABLE_H_#define MinTableSize 10000#define Prime 10007typedef unsigned int Index;typedef Index Position;struct HashTbl;typedef struct HashTbl* HashTable;typedef int ElementType;typedef struct HashEntry Cell;enum KindOfEntry {Legitimate ,Empty,Deleted};HashTable InitializeTable(int TableSize);void DestroyTable(HashTable H);Position Find(ElementType Key, HashTable H);void Insert(ElementType Key, HashTable H);ElementType Retrieve(Position P,HashTable H);HashTable Rehash(HashTable H);#endif

hashtable.c

#include<stdio.h>#include<stdlib.h>#include"hashtable.h"struct HashEntry{    ElementType Element;    enum KindOfEntry Info;};struct HashTbl{    int TableSize;    Cell *TheCells;};int Hash(ElementType Key, int TableSize){    return Key%TableSize;}HashTable InitializeTable(int TableSize){    HashTable H;    int i;    if (TableSize < MinTableSize)    {        printf("ERROR!\n");        return NULL;    }    H = (HashTable)malloc(sizeof(HashTbl));    if (H == NULL)    {        printf("FAILURE!\n");        exit(EXIT_FAILURE);    }    H->TableSize = Prime;//Prime随TableSize变化而变化    H->TheCells = (Cell *)malloc(sizeof(Cell)*H->TableSize);    if (H->TheCells == NULL)    {        printf("FAILURE!\n");        exit(EXIT_FAILURE);    }    for (i = 0; i < H->TableSize; i++)        H->TheCells[i].Info = Empty;    return H;}void DestroyTable(HashTable H){    if (H)        free(H->TheCells);}Position Find(ElementType Key, HashTable H){    Position CurrentPos;    int CollisionNum;    CollisionNum = 0;    CurrentPos = Hash(Key, H->TableSize);    while (H->TheCells[CurrentPos].Info != Empty &&        H->TheCells[CurrentPos].Element != Key)    {        CurrentPos += 2 * ++CollisionNum - 1;        if (CurrentPos >= H->TableSize)            CurrentPos -= H->TableSize;    }    return CurrentPos;}void Insert(ElementType Key, HashTable H){    Position Pos;    Pos = Find(Key, H);    if (H->TheCells[Pos].Info != Legitimate)    {        H->TheCells[Pos].Info = Legitimate;        H->TheCells[Pos].Element = Key;    }}ElementType Retrieve(Position P, HashTable H){    if(H && H->TheCells[P].Info==Legitimate)        return H->TheCells[P].Element;    else        return 0;}HashTable Rehash(HashTable H){    int i, OldSize;    Cell *OldCells;    OldCells = H->TheCells;    OldSize = H->TableSize;    H = InitializeTable(2 * OldSize);    for (i = 0; i < OldSize; i++)        if (OldCell[i].Info == Legitimate)            Insert(OldCells[i].Element, H);    free(OldCells);    return H;}
0 0