散列表的实现-开放定址法

散列表有两种实现方式,为分离链表法与开放定址法;其中以开放定址法需要选取适当的散列函数与冲突函数来实现,根据开放定址法散列函数,大致分为线性探测、平方探测、双散列等;

下面给出平方探测的开放定址法的实现:


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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值