Hash散列

#define MinTableSize 10//最小表大小
#define NULLUNM -32789
struct ListNode;
struct HashTbl;
typedef struct ListNode *Position;
typedef Position List;
typedef struct HashTbl *HashTable;


struct ListNode//链表
{
	int Element;
	Position Next;
};

struct HashTbl//hash表
{
	int TableSize;//hash表的大小(链表个数)
	List *TheLists;//链表类型的数组。TheList是数组首地址
};

int IsPrimeNum1(int X)
{
	if (X == 1 || X == 2)
	{
		return 1;
	}
	else
	{
		for (int i = 2; i < X; i++)
		{
			if (X%i == 0)
			{
				return 0;
			}
		}
		return 1;
	}
}

int NextPrime(int inputSize)
{
	int input = inputSize;
	if (IsPrimeNum1(inputSize))
	{
		return inputSize;
	}
	else
	{
		while (!IsPrimeNum1(input))
		{
			input++;
		}
		return input;
	}
}

HashTable InitializeTable(int TableSize)
{
	HashTable H;
	int i;

	if (TableSize < MinTableSize)
	{
		return NULL;
	}
	H = (HashTable)(malloc(sizeof(struct HashTbl)));
	if (H == NULL)
	{
		return NULL;
	}

	H->TableSize = NextPrime(TableSize);
	H->TheLists = (List*)(malloc(sizeof(struct ListNode)*H->TableSize));
	if (H->TheLists == NULL)
	{
		return NULL;
	}

	for (i = 0; i < H->TableSize; i++)
	{
		H->TheLists[i] = (List)(malloc(sizeof(struct ListNode)));
		if (H->TheLists[i] == NULL)
		{
			return NULL;
		}
		else
		{
			H->TheLists[i]->Next = NULL;
			H->TheLists[i]->Element = NULLUNM;
		}
	}
	printf_s("Initialized\n");
	return H;
}

typedef unsigned int Index;
Index Hash(const int key, int TableSize)
{
	Index hash;
	int tmp = key;
	if (key < 0)
		tmp = key * -1;
	hash = tmp % TableSize;
	return hash;
}

Position Find(const int key, HashTable H)
{
	Position p;
	List L;
	Index index = Hash(key, H->TableSize);
	L = H->TheLists[index];
	p = L;
	while (p != NULL && p->Element != key&&p->Element!= NULLUNM)
	{
		p = p->Next;
	}
	return p;
}

void Insert(const int key, HashTable H)
{
	Position Pos, NewCell;
	List L;
	Pos = Find(key,H);
	if (Pos == NULL)
	{
		NewCell = malloc(sizeof(struct ListNode));
		L = H->TheLists[Hash(key, H->TableSize)];
		NewCell->Next = L->Next;
		NewCell->Element = key;
		L->Next = NewCell;
	}
	else if(Pos->Element= NULLUNM)
	{
		Pos->Element = key;
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值