#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
using namespace std;
#define HASH_LEN 100
typedef struct Node
{
char* key;
char* value;
struct Node *next;
}Node;
static Node* hashtab[HASH_LEN];
unsigned int hash(char * key)
{
unsigned int hash =0;
char *str=key;
while(*str++)
{
hash= ((hash<<5)+hash);
}
hash=hash % HASH_LEN;
return hash;
}
void inithash()
{
int i=0;
for(;i<HASH_LEN;i++)
{
hashtab[i]=NULL;
}
}
Node* LOOKUP(char* KEY)
{
unsigned int index=hash(KEY);
Node *np=hashtab[index];
for(;np!=NULL;np=np->next)
{
if( !strcmp(np->key,KEY) )
{
return np;
}
}
return NULL;
}
char* GETVALUE(char* KEY)
{
Node *np=LOOKUP(KEY);
if(np == NULL)
return NULL;
else
return np->value;
}
char* straloc(char* str)
{
int l=strlen(str)+1;
char* dest=(char*)malloc(sizeof(char)*l);
strcpy(dest,str);
return dest;
}
bool install(char* key,char* value)
{
bool ret =0;
Node* np;
int index;
// unsigned int index= hash(key);
if( (np=LOOKUP(key)) ==NULL)
{
index=hash(key);
np=(Node*)malloc(sizeof(Node));
if(np==NULL)
return ret;
np->key=straloc(key);
if(np->key==NULL)
return ret;
np->next=hashtab[index];
hashtab[index]=np;
}else{
if(np->value == value)
{
free(np->value);
}else{
index=hash(key);
np=(Node*)malloc(sizeof(Node));
if(np==NULL)
return ret;
np->key=straloc(key);
if(np->key==NULL)
return ret;
np->next=hashtab[index];
hashtab[index]=np;
}
}
np->value=straloc(value);
if(np->value==NULL) return 0;
return ret =1;
}
void showtab()
{
int i;
Node *np;
for(i=0;i<HASH_LEN;i++)
{
np=hashtab[i];
if(NULL ==hashtab[i])
{
printf("NULL\n");
}
while(np!=NULL)
{
printf("np->key==%s np->value==%s\n",np->key,np->value);
np=np->next;
}
}
}
void cleanup()
{
int i;
Node *np,*tem;
for(i=0;i<HASH_LEN;i++)
{
np=hashtab[i];
while(np!=NULL)
{
tem=np->next;
free(np->key);
free(np->value);
free(np);
np=tem;
}
}
}
int main(int argc,char* argv[])
{
int i=0;
char *str;
char* key[]={"one","two","three"};
char* value[]={"my","heart","will","go","on"};
Node* np;
inithash();
np=LOOKUP("one");
printf("np ==%p\n",np);
printf("%d\n",install("one","my") );
np=LOOKUP("one");
printf("np ==%p \n",np);
str=GETVALUE("one");
printf("%s\n",str);
printf("%d\n",install("one","off") );
np=LOOKUP("one");
printf("np ==%p \n",np);
str=GETVALUE("one");
printf("%s\n",str);
printf("\n");
printf("%d\n",install("one","heart") );
np=LOOKUP("one");
printf("np ==%p \n",np);
str=GETVALUE("one");
printf("%s\n",str);
return 0;
}