c-简单hash 链法 ---参考魔法学院

#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值