HashClose.h
#pragma once
#include <stddef.h>
size_t HashMaxSize=1000;
typedef enum Stat {
Empty,
Valid,
Invalid // 当前元素被删除了
} Stat;
typedef int KeyType;
typedef int ValType;
typedef size_t (*HashFunc)(KeyType key);
typedef struct HashElem {
KeyType key;
ValType value;
Stat stat; // 引入一个 stat 标记来作为是否有效的标记
} HashElem;
typedef struct HashTable {
HashElem *data;
size_t size;
HashFunc hash_func;
} HashTable;
void HashInit(HashTable* ht, HashFunc fp);
int HashInsert(HashTable* ht, KeyType key, ValType value);
// 输入key, 查找对应key的value.
int HashFind(HashTable* ht, KeyType key, ValType* value);
void HashRemove(HashTable* ht, KeyType key);
int HashEmpty(HashTable* ht);
size_t HashSize(HashTable* ht);
void HashDestroy(HashTable* ht);
HashClose.c
ShowTable(&ht,(char*)"insert 600 element");
printf("HashMaxSize:%lu\n", HashMaxSize);
}
void TestRemove()
{
TEST_HEADER;
HashTable ht;
HashInit(&ht,HashFun);
int i;
for(i=0;i<600;i++)
{
HashInsert(&ht,i,i*4);
}
ShowTable(&ht,(char*)"first insert 600 element");
for(i=0;i<600;i++)
{
HashRemove(&ht,i);
}
ShowTable(&ht,(char*)"remove 600 element");
for(i=0;i<600;i++)
{
HashInsert(&ht,i,i*4);
}
ShowTable(&ht,(char*)"second insert 600 element");
}
void TestDestory()
{
TEST_HEADER;
HashTable ht;
HashInit(&ht,HashFun);
HashInsert(&ht,3,24);
HashDestroy(&ht);
ShowTable(&ht,(char*)"Destroy");
}
int main()
{
TestInit();
TestInsert();
TestRemove();
TestDestory();
return 0;
}
Makefile
HashClose: HashClose.c
gcc -o $@ $^
.PHONY:clean
clean:
rm HashClose
运行结果:
[abc123@localhost hash_close]$ ./HashClose
=================TestInit=================
-------HashInit-------
HashTable
data : 0xade010
size : 0
func : 0x400610
=================TestInsert=================
-------before insert -------
HashTable
data : 0xae0f00
size : 0
func : 0x400610
HashMaxSize:1000
-------insert 600 element-------
HashTable
data : 0xae3df0
size : 600
func : 0x400610
HashMaxSize:2001
=================TestRemove=================
-------first insert 600 element-------
HashTable
data : 0xae9bd0
size : 600
func : 0x400610
-------remove 600 element-------
HashTable
data : 0xae9bd0
size : 0
func : 0x400610
-------second insert 600 element-------
HashTable
data : 0xae9bd0
size : 600
func : 0x400610
=================TestDestory=================
-------Destroy-------
HashTable
data : (nil)
size : 0
func : (nil)
[abc123@localhost hash_close]$