写给自己看的散列表(2):开放定址法

1.定义
在开放定址法中,用一个数组来存储散列表的元素,因此散列表结构Htable中有一个数组(指针)CellArray,数组中的每一个元素都是一个Hcell,Hcell中除了有data外,还有一个enum类型的字段来记录该元素的“状态”,为空、被使用或者已删除。

enum entrykind {Legitimate, Empty, Deleted};

typedef struct cell
{
	eletype data;
	enum entrykind info;
}Hcell;

typedef struct table
{
	int size;
	Hcell *CellArray;
}Htable;

2.新建一个散列表
注意要将数组CellArray中的每一个元素的状态info设置为Empty。

Htable *CreateHashTable(int tsize)
{
	Htable *H;

	if (tsize < MinSize) {
		printf("Table size must >= %d\n", MinSize);
		return NULL;
	}

	H = malloc(sizeof(Htable));
	if (H == NULL) {
		printf("Create table failed\n");
		return NULL;
	}
	
	H->size = NextPrime(tsize);
	H->CellArray = malloc(sizeof(Hcell) * H->size);
	if (H->CellArray == NULL) {
		printf("Out of space\n");
		return NULL;
	}

	Hcell *pcell;
	pcell = H->CellArray;
	for (int i = 0; i < H->size; i++) {
		pcell->info = Empty;
		pcell++;
	}

	return H;
}

3.插入
用到的Find和Hash函数与写给自己看的散列表(1):分离链接法中相同,特别点在于将info设置为Legitimate,表示该存储空间被使用了。

void Insert(Htable *H, eletype key)
{
	uint pos;
	pos = Find(H, key);
	if (H->CellArray[pos].info != Legitimate) {
		H->CellArray[pos].info = Legitimate;
		//strcpy(H->CellArray[pos].data, key);
		H->CellArray[pos].data = key;
	}
}

猜你喜欢

转载自blog.csdn.net/u013213111/article/details/88870924
今日推荐