705. 设计哈希集合

#define HASH_SIZE 10009

typedef enum { Legitimate, Empty, Deleted } Entry_type;

struct hash_entry
{
	int val;
	Entry_type info;
};

typedef struct 
{
	int size;
	struct hash_entry* cells;
} MyHashSet;

int hash_function(MyHashSet* obj, int key)
{
	return key % obj->size;
}

int find(MyHashSet* obj, int key)
{
	int curr_pos, new_pos, coll_num;

	coll_num = 0;
	curr_pos = new_pos = hash_function(obj, key);

	while (obj->cells[new_pos].info != Empty && obj->cells[new_pos].val != key)
	{
		coll_num++;
		if (coll_num % 2 != 0)
		{
			new_pos = curr_pos + ((coll_num + 1) / 2 * (coll_num + 1) / 2);
			while (new_pos >= obj->size)
			{
				new_pos -= obj->size;
			}
		}
		else
		{
			new_pos = curr_pos - (coll_num / 2 * coll_num / 2);
			while (new_pos < 0)
			{
				new_pos += obj->size;
			}
		}
	}

	return new_pos;
}

MyHashSet* myHashSetCreate()
{
	MyHashSet* obj = malloc(sizeof(MyHashSet));

	obj->size = HASH_SIZE;
	obj->cells = malloc(obj->size * sizeof(struct hash_entry));
	for (int i = 0; i < obj->size; i++)
	{
		obj->cells[i].info = Empty;
	}

	return obj;
}

void myHashSetAdd(MyHashSet* obj, int key)
{
	int pos = find(obj, key);

	if (obj->cells[pos].info != Legitimate)
	{
		obj->cells[pos].val = key;
		obj->cells[pos].info = Legitimate;
	}

	return;
}

bool myHashSetContains(MyHashSet* obj, int key)
{
	int pos = find(obj, key);

	if (obj->cells[pos].info == Legitimate && obj->cells[pos].val == key)
	{
		return true;
	}
	else
	{
		return false;
	}
}

void myHashSetRemove(MyHashSet* obj, int key)
{
	int pos = find(obj, key);

	if (obj->cells[pos].info == Legitimate)
	{
		obj->cells[pos].info = Deleted;
	}
}

void myHashSetFree(MyHashSet* obj)
{
	free(obj);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值