欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

哈希表闭散列(代码实现)

程序员文章站 2024-03-22 08:49:22
...

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 [email protected]  $^
.PHONY:clean
clean:
	rm HashClose


运行结果:

[[email protected] 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)
[[email protected] hash_close]$