#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);
}
705. 设计哈希集合
最新推荐文章于 2024-08-03 20:10:04 发布