散列表有两种实现方式,为分离链表法与开放定址法;其中以开放定址法需要选取适当的散列函数与冲突函数来实现,根据开放定址法散列函数,大致分为线性探测、平方探测、双散列等;
下面给出平方探测的开放定址法的实现:
// hash: Open-addressing hasing
typedef unsigned int Index;
typedef Index Position;
struct HashEntry;
typedef struct HashEntry Cell;
struct HashTbl;
typedef struct HashTbl *HashTable;
enum KindOfEntry { Legitimate, Empty, Delete };
struct HashEntry
{
ElementType element;
enum KindOfEntry info;
};
struct HashTbl
{
int tableSize;
Cell *theCells;
};
HashTable InitializeTable( int tableSize )
{
HashTable H;
if ( tableSize < MinTableSize )
{
printf( "Table size too small" );
return NULL;
}
/* Allocate table */
H = (HashTable)malloc( sizeof(sizeof HashTbl) );
if ( H == NULL )
{
printf( "Out of space" );
return NULL;
}
H->tableSize = NextPrime( tableSize );
/* Allocate array of cells */
H->theCells = (Cell *)malloc( sizeof(struct Cell) * H->talbeSize );
if ( H->theCells == NULL )
{
printf( "Out of space" );
return NULL;
}
for ( int i = 0; i < H->tableSize; ++i )
H->theCells[i].info = Empty;
return H;
}
void Find( ElementType key, HashTable H )
{
// 不考虑表满情况
Position currentPos;
int collisionNum; // 冲突次数
cullisionNum = 0;
currentPos = Hash( key, H->tableSize );
while ( H->theCells[currentPos].Info != Empty &&
H->theCells[currentPos].element != key )
{
currentPos += 2 * ++cullisionNum - 1;
if ( currentPos >= H->tableSize )
cullisionNum -= H->tableSize;
}
return currentPos;
}
void Insert( ElementType key, HashTable H )
{
Position p;
p = Find( key, H );
if ( H->theCells[p].info != Legitimate )
{
H->theCells[p].info = Legitimate;
H->theCells[p].element = key;
}
}