/*
*散列表开放定址法的一些操作。
*/
#include <stdio.h>
#include <stdlib.h>
typedef unsigned int Index;
typedef Index Position;
struct HashTb1;
typedef struct HashTb1 *HashTable;
#define MinTableSize 10
enum KindOfEntry {Legitimate, Empty, Delwted};
struct HashEntry
{
int Element;
enum KindOfEntry Info;
};
typedef struct HashEntry Cell;
struct HashTb1
{
int TableSize;
Cell *TheCells;
};
static int NextPrime( int N )
{
if( N % 2 == 0 )
N++;
return N;
}
static Index Hash(int key, int TableSize)
{
return key % TableSize;
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
int i;
if (TableSize < MinTableSize)
{
printf("Table size is too small.\n");
return NULL;
}
/* Allocate table */
H = (HashTable)malloc(sizeof(struct HashTb1));
if (H == NULL)
{
printf("out of space!!!\n");
}
H->TableSize = NextPrime(TableSize);
/* Allocate arrary of cells */
H->TheCells = (Cell *)malloc(sizeof(Cell) * H->TableSize);
if (H->TheCells == NULL)
{
printf("out of space!!!");
}
for (i = 0; i < H->TableSize; i++)
H->TheCells[i].Info = Empty;
return H;
}
Position Find(int Key, HashTable H)
{
Position CurrentPos;
int CollisionNum;
CollisionNum = 0;
CurrentPos = Hash(Key, H->TableSize);
/* probably need strcmp!! */
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(int 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;
}
}
void PrintHash(HashTable H)
{
int i;
for (i = 0; i < H->TableSize; i++)
{
if (H->TheCells[i].Info == Legitimate)
{
printf("%d, ", H->TheCells[i].Element);
}
}
}
int main(void)
{
int num = 19;
HashTable Hash = InitializeTable(19);
Insert(5, Hash);
Insert(6, Hash);
Insert(7, Hash);
PrintHash(Hash);
return 0;
}
散列表开放定址法的初始化、插入、打印等函数(c)
最新推荐文章于 2021-03-30 14:16:54 发布