数据结构---散列(哈希表)

本文以C语言描述散列,其中哈希函数可根据自己需要更改,以下是源代码:


#include "HashSep.h"

typedef uint64_t Index;
static Index Hash(const char *Key, uint64_t TableSize)
{
	Index HashVal = 0;
	while ('\0' != *Key)
	{
		HashVal = (HashVal << 5) + *Key++;
	}
	return HashVal%TableSize;
}

static bool IsPrime(uint64_t n)
{
	if ((1 == n) || (2 == n) || (0 == (n % 2)))
		return false;
	for (uint64_t i = 3; i*i < n; i += 2)
	{
		if (0 == n%i)
			return false;
	}

	return true;
}
static uint64_t NextPrime(uint64_t n)
{
	while (!IsPrime(n++));
	return --n;
}
HashTable InitializeTable(uint64_t TableSize)
{
	HashTable H;
	if (TableSize < MINTABLESIZE)
	{
		printf("Table size is too small!\r\n");
		return NULL;
	}

	H = (HashTable)malloc(sizeof(HashTbl));
	if (NULL == H)
	{
		printf("Out of space!\r\n");
		return NULL;
	}

	H->TableSize = NextPrime(TableSize);
	H->TheLists = malloc(H->TableSize * sizeof(List));
	if (NULL == H->TheLists)
	{
		printf("Out of size!\r\n");
		return NULL;
	}

	for (uint64_t i = 0; i < H->TableSize; i++)
	{
		H->TheLists[i] = (Position)malloc(sizeof(ListNode));
		if (NULL == H->TheLists[i])
		{
			printf("Out of space!\r\n");
			return NULL;
		}
		H->TheLists[i]->Next = NULL;
	}

	return H;
}
void DestoryTable(HashTable H);

Position Find(HashTable H, ElementType Key)
{
	Position P;
	List L;

	L = H->TheLists[Hash(Key, H->TableSize)];
	P = L->Next;
	
	while (NULL != P && strcmp(Key, P->Element))
	{
		P = P->Next;
	}
	return P;
}
void Insert(HashTable H, ElementType Key)
{
	Position Pos, NewCell;
	List L;

	Pos = Find(H, Key);
	if (NULL == Pos)
	{
		NewCell = (Position)malloc(sizeof(ListNode));
		if (NULL == NewCell)
		{
			printf("Out of space!\r\n");
		}
		else
		{
			L = H->TheLists[Hash(Key, H->TableSize)];
			NewCell->Next = NULL;
			NewCell->Element = Key;
			L->Next = NewCell;
		}
	}
}
ElementType Retrieve(Position P);


#ifndef __HashSep_H_
#define __HashSep_H_

#include "stdint.h"
#include "stdio.h"
#include "malloc.h"
#include "string.h"
#include "stdbool.h"
#include "stdlib.h"

#define MINTABLESIZE 3

typedef char *ElementType;
typedef struct node
{
	ElementType Element;
	struct node *Next;
} ListNode;
typedef ListNode *Position;
typedef Position List;

typedef struct
{
	uint64_t TableSize;
	List *TheLists;
} HashTbl;
typedef HashTbl *HashTable;


HashTable InitializeTable(uint64_t TableSize);
void DestoryTable(HashTable H);
Position Find(HashTable H, ElementType Key);
void Insert(HashTable H, ElementType Key);
ElementType Retrieve(Position P);

#endif



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值