I have previously written an article about the application of a hash table in the retrieval of SIP phones. I have read the code and learned the basic ideas and hash functions of a hash table. The following is a summary of the content in the book C algorithm. Only a small part will be summarized and updated later. I am also learning the application of mind map. I have used it in my previous blog. The following uses the Mind Map to summarize the hash table content:
The following describes a typical string hash function:
/* Hashpjw. C */unsigned int hashpjw (const void * Key) {const char * PTR; unsigned int val; val = 0; PTR = key; while (* PTR! = '\ 0') {unsigned int TMP; val = (Val <4) + (* PTR); If (TMP = (Val & 0xf0000000 )) {val = Val ^ (TMP> 24); val = Val ^ TMP;} PTR ++;} return Val % prime_tblsiz // Number of buckets}Chain hash table structure
Implementation and definition of chained hash tables
/* Chtbl. H */# ifndef chtbl_h # define chtbl_h # include <stdlib. h>/* header file of a single-chain table */# include "list. H "/* defines the struct of a chain hash table */typedef struct chtbl _ {int buckets;/* Number of buckets allocated to the hash table */INT (* H) (const void * Key);/* hash function pointer H */INT (* match) (const void * key1, const void * key2 ); /* determine whether two keys match */void (* destroy) (void * data);/* release memory space */INT size; /* Number of Members */list * Table;/* head pointer of the bucket in the hash table */} chtbl;/* function interface */INT chtbl_init (chtbl * htbl, int buckets, INT (* H) (const void * Key), INT (* match) (const void * key1, const void * key2), void (* destroy) (void * Data); int chtbl_destroy (chtbl * htbl); int chtbl_insert (chtbl * htbl, const void * data); int chtbl_remove (chtbl * htbl, void ** data); int chtbl_lookup (const chtbl * htbl, void ** data); # define chtbl_size (chtbl * htbl) (htbl)-> size) # endif
/* Chtbl_c */# include <stdlib. h> # include <string. h> # include ". /include/list. H "# include ". /include/chtbl. H "/* initialize the hash table structure body */INT chtbl_init (chtbl * htbl, int buckets, INT (* H) (const void * Key), INT (* match) (const void * key1, const void * key2), void (* destroy) (void * Data) {int I; /* apply for Bucket */If (htbl-> table = (list *) malloc (buckets * sizeof (list) = NULL) {return-1 ;} /* initialize the hash table */htbl-> buckets = B Uckets; for (I = 0; I <buckets; I ++) {list_init (& htbl-> table [I], destroy);} htbl-> H = h; htbl-> match = match; htbl-> destroy = destroy; htbl-> size = 0; return 0;}/* destroy the hash table */void chtbl_destroy (chtbl * htbl) {int I; If (htbl = NULL) return;/* destroy each bucket */for (I = 0; I