开放地址法散列表ADT

时间:2021-04-21 21:20:22

数据结构定义如下:

 typedef unsigned int Index;
typedef Index Position; struct HashTbl;
typedef struct HashTbl *HashTable; 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); enum KindOfEntry {Legitimate, Empty, Deleted};
struct HashEntry{
ElementType Element;
enum KindOfEntry Info;
};
typedef struct HashEntry Cell; struct HashTbl{
int TableSize;
Cell *TheCells;
};

初始化函数代码如下:

 HashTable InitializeTable(int TableSize){
HashTable H;
int i; if(TableSize < MinTableSize){
printf("Table size too small\n");
return NULL;
} H = malloc(sizeof(struct HashTbl));
H->TableSize = NextPrime(TableSize);
H->TheCells = malloc(H->TableSize * sizeof(Cell)); for(i=; i<H->TableSize; i++)
H->TheCells[i].Info = Empty; return H;
}

Find函数实现代码如下:

 Position Find(ElementType Key, HashTable H){
Position Pos;
int i; i=;
Pos = Hash(Key, H->TableSize);
while(H->TheCells[Pos].Info != Empty
&& H->TheCells[Pos].Element != Key){
Pos += (++i)*-;
if(Pos >= H->TableSize)
Pos -= H->TableSize;
}
return Pos;
}

Insert函数代码实现如下:

 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;
}
}

Rehash函数代码实现如下:

 HashTable rehash(HashTable H){
int i, OldSize = H->TableSize;
HashTable OldH = H;
Cell *OldCells = H->TheCells; H = InitializeTable(*OldSize);
for(int i=; i<OldSize; i++){
if(OldCells[i].Info == Legitimate)
Insert(OldCells[i].Element, H);
} free(OldH);
free(OldCells);
return H;
}