哈希表的分散链实现

#include <stdio.h>
#include <stdlib.h>
#define MinSize 10
struct ListNode;
typedef struct ListNode* Position;
struct HashTabl;
typedef struct HashTbl* HashTable;

struct ListNode {
	int element;
	Position next;
};

typedef Position List;
struct HashTbl {
	int TableSize;
	List* TheLists;
};

HashTable InitializeTable(int TableSize);
void DestroyTable(HashTable H);
Position Find(int Key, HashTable H);
int Retrieve(Position P);

HashTable Initialize(int TableSize)
{
	if (TableSize < MinSize)
	{
		Error("No Space!!");
		return NULL;
	}
	HashTable H = malloc(sizeof(struct HashTbl));
	if (H == NULL)
		FatalError("No Space!!");

	H->TableSize = TableSize;
	H->TheLists = malloc(sizeof(List) * TableSize);
	if (H->TheLists == NULL)
		FatalError("No Space!!");

	int i;
	for (i = 0; i < TableSize; i++)
	{
		H->TheLists[i] = malloc(sizeof(struct ListNode));
		if (H->TheLists[i] == NULL)
			FatalError("No Space!!");
		else
			H->TheLists[i] = NULL;
	}

	return H;
}

int Hash(int x, int TableSzie);

Position Find(int x, HashTable H)
{
	int index = Hash(x, H->TableSize);
	List L = H->TheLists[index];
	Position P = L->next;

	while (P->element != x && P->next != NULL)
		P = P->next;

	return P;
}

void Insert(int x, HashTable H)
{
	int index = Hash(x, H->TableSize);
	List L = H->TheLists[index];
	Position P = Find(x, H);
	if (P == NULL)//先检查里面有没有过
	{
		Position new = malloc(sizeof(struct ListNode));
		if (new == NULL)
			Error("No Space!!");
		else
		{
			new->element = x;
			new->next = L->next;
			L->next = new;
		}
	}
}

void Delete(int x, HashTable H)
{
	Position pos = Find(x, H);
	if (pos != NULL)
	{
		Position temp = pos->next;
		pos->next = temp->next;
		free(temp);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值