#include <stdlib.h>
#include <stdio.h>
#include <string.h> typedef struct _hashnode{
int val;
char * key;
struct _hashnode * next;
} hashnode; //存储hash表大小
#define HASHTABLE_MAX 1000
//form php source
static inline unsigned int hashtable_hash_str(const char *arKey)
{
register unsigned int hash = ;
unsigned int nKeyLength=strlen(arKey);
/* variant with the hash unrolled eight times */
for (; nKeyLength >= ; nKeyLength -= ) {
hash = ((hash << ) + hash) + *arKey++;
hash = ((hash << ) + hash) + *arKey++;
hash = ((hash << ) + hash) + *arKey++;
hash = ((hash << ) + hash) + *arKey++;
hash = ((hash << ) + hash) + *arKey++;
hash = ((hash << ) + hash) + *arKey++;
hash = ((hash << ) + hash) + *arKey++;
hash = ((hash << ) + hash) + *arKey++;
}
switch (nKeyLength) {
case : hash = ((hash << ) + hash) + *arKey++; /* fallthrough... */
case : hash = ((hash << ) + hash) + *arKey++; /* fallthrough... */
case : hash = ((hash << ) + hash) + *arKey++; /* fallthrough... */
case : hash = ((hash << ) + hash) + *arKey++; /* fallthrough... */
case : hash = ((hash << ) + hash) + *arKey++; /* fallthrough... */
case : hash = ((hash << ) + hash) + *arKey++; /* fallthrough... */
case : hash = ((hash << ) + hash) + *arKey++; break;
case : break;
}
return hash;
} hashnode * hashtable_create(){
hashnode * hashs=(hashnode *)malloc(HASHTABLE_MAX * sizeof(hashnode *));
memset(hashs, , HASHTABLE_MAX * sizeof(hashnode *));
return hashs;
} void hashtable_set(hashnode* hashlist[],const char * b,int val){
unsigned int pos=hashtable_hash_str(b)%HASHTABLE_MAX;
hashnode * hashp= hashlist[pos];
while(hashp){
if(strcmp(hashp->key,b)==){
break;
}
hashp=hashp->next;
}
if(!hashp){
hashnode * p=(hashnode *)malloc(sizeof(hashnode));
memset(p,,sizeof(hashnode));
char * ikey=(char *)malloc(sizeof(char)*(strlen(b)+));
strcpy(ikey,b);
p->key=ikey;
p->val=val;
p->next=hashlist[pos];
hashlist[pos]=p;
}else{
hashp->val=val;
}
} int hashtable_get(hashnode* hashlist[],const char * b,int *r){
unsigned int pos=hashtable_hash_str(b)%HASHTABLE_MAX;
hashnode * hashp= hashlist[pos];
while(hashp){
if(strcmp(hashp->key,b)==){
*r=hashp->val;
return ;
}
hashp=hashp->next;
}
return ;
} void hashtable_unset(hashnode* hashlist[],const char * b){
unsigned int pos=hashtable_hash_str(b)%HASHTABLE_MAX;
hashnode * hashp= hashlist[pos];
hashnode * phashp=NULL;
while(hashp){
if(strcmp(hashp->key,b)==){
if(phashp)
phashp->next=hashp->next;
else
hashlist[pos]=hashp->next;
free(hashp->key);
free(hashp); }
phashp=hashp;
hashp=hashp->next;
}
}
void hashtable_free(hashnode* hashlist[]){
int i=;
while(i<HASHTABLE_MAX){
hashnode * temp=hashlist[i];
while(temp){
hashnode * tt=temp->next;
free(temp->key);
free(temp);
temp=tt;
}
i++;
}
hashlist=NULL;
} int main(){
//使用
hashnode * ht=hashtable_create();
hashtable_set(ht,"abc",);
int r=;
if(hashtable_get(ht,"abc",&r))
printf("%d",r);
hashtable_unset(ht,"abc");
if(hashtable_get(ht,"abc",&r))
printf("%d",r);
//释放所占内存
hashtable_free(ht);
return EXIT_SUCCESS;
}