关闭

简单hash就是数组加链表

标签: insertnullstructlistc
2848人阅读 评论(0) 收藏 举报

    简单的hash就是用数组加链表的组合来实现,这种hash很简单,但hash的思想在那。

    贴出代码:

hash.h:

#ifndef _HASH_H_
#define _HASH_H_

typedef struct _ListNode
{
	struct _ListNode *prev;
	struct _ListNode *next;
	void *data;
}ListNode;

typedef ListNode *List;
typedef ListNode *Position;

typedef struct _HashTbl
{
	int TableSize;
	List *Thelists;
}HashTbl;

int Hash( void *key, int TableSize );
HashTbl *InitHash( int TableSize );
void Insert( void *key, HashTbl *HashTable );
Position Find( void *key, HashTbl *HashTable );
void Destory( HashTbl *HashTable );
void *Retrieve( Position P );



#endif


hash.c:

#include <stdio.h>
#include <stdlib.h>
#include "hash.h"

int Hash( void *key, int TableSize )
{
	char c;
	int i;
	int hval = 0;

	for( i = 1;(c = *(char *)key++) != 0; i++)
		hval += c*i;
	return (hval%TableSize);
}

HashTbl *InitHash( int TableSize )
{
	int i;
	HashTbl *HashTable;
	HashTable = malloc(sizeof(HashTbl));
	if( NULL == HashTable )
	{
		printf("HashTable malloc error\n");
		return;
	}

	HashTable->TableSize = TableSize;
	
	HashTable->Thelists = malloc(sizeof(List)*TableSize);
	if( NULL == HashTable->Thelists )
	{
		printf("HashTable malloc error\n");
		return;
	}

	for( i = 0; i < TableSize; i++)
	{
		HashTable->Thelists[i] = malloc(sizeof(ListNode));
		if( NULL == HashTable->Thelists[i] )
		{
			printf("HashTable malloc error\n");
			return;
		}
		else
		{
			HashTable->Thelists[i]->next = NULL;
			HashTable->Thelists[i]->prev = NULL;
		}	
	}

	return HashTable;
}

Position Find( void *key, HashTbl *HashTable )
{
	int i,j;
	List L;
	Position P;
	i = Hash(key,HashTable->TableSize);
	L = HashTable->Thelists[i];
	P = L->next;
	while( P != NULL && P->data != key )
		P = P->next;

	return P;
}

void Insert( void *key, HashTbl *HashTable )
{
	Position P,tmp;
	List L;
	P = Find(key,HashTable);
	
	if( NULL == P )
	{
		tmp = malloc(sizeof(ListNode));
		if( NULL == tmp )
		{
			printf("malloc error\n");
			return;
		}
		L = HashTable->Thelists[Hash(key,HashTable->TableSize)];
		tmp->data = key;
		tmp->next = L->next;
		if(L->next != NULL)
			L->next->prev = tmp;
		tmp->prev = L;
		L->next = tmp;
	}
	else
		printf("the key already exist\n");
}

void *Retrieve( Position P )
{
	return P->data;
}

void Destory( HashTbl *HashTable )
{
	int i;
	List L;
	Position tmp,tmp2;
	for( i = 0; i < HashTable->TableSize; i++)
	{
		L = HashTable->Thelists[i];
		tmp = L->next;
		while(tmp->next != NULL)
		{
			tmp2 = tmp->next;
			free(tmp);
			tmp = tmp2;
		}
		free(L);
	}
	free(HashTable);
}

void main( void )
{
	HashTbl *HashTable;
	HashTable = InitHash(31);
	Insert("a",HashTable);
	Insert("b",HashTable);	
	Insert("b",HashTable);
	Position P;
	P = Find("a",HashTable);
	printf("%s\n",Retrieve(P));
}



 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:469962次
    • 积分:7396
    • 等级:
    • 排名:第3067名
    • 原创:107篇
    • 转载:0篇
    • 译文:1篇
    • 评论:98条
    博客专栏
    最新评论