散列表(冲突用链表解决)

#include "stdafx.h"
#include<iostream>
#include<cmath>
using namespace std;
#ifndef _HashSsp_
struct ListNode;
typedef struct ListNode *Position;
struct HashTbl;
typedef struct HashTbl *HashTable;

HashTable InitializeTable(int TableSize);
void DestroyTable(HashTable H);
Position Find(int key, HashTable H);
void Insert(int key, HashTable H);
int Retrieve(Position P);
#endif // _HashSsp_
#define MinTableSize 10
struct ListNode
{
	int key;
	Position Next;
};

typedef Position List;

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

int NextPrime(int n)
{
	if (n % 2 == 0) n++;               //1.排除掉偶数
	for (;; n += 2)
	{
		bool isPrime = 1;              //2.标志位
		for(int i=3;i*i<=n;i+=2)
			if (n%i == 0) {
				isPrime = 0;
				break;
			}
		if (isPrime)
			return n;
	}
}

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

	if (TableSize < MinTableSize)
	{
		cout << "Table is too small";
		return NULL;
	}

	H = (HashTable)malloc(sizeof(HashTbl));                //1.初始化散列表地址
	if (H == NULL)
		cout << "out of space";
	H->TableSize = NextPrime(TableSize);                 //2.用素数初始化散列表大小
	H->TheLists = (List *)malloc(sizeof(List)*H->TableSize);       //3.申请结构指针数组的空间并给出地址
	if (H->TheLists == NULL)
		cout << "out of space";

	for ( i = 0; i < H->TableSize; i++)                //4.初始化每个链表表头
	{
		H->TheLists[i] = (List)malloc(sizeof(ListNode));
		if (H->TheLists[i] == NULL)
			cout << "out df space";
		else
			H->TheLists[i]->Next = NULL;
	}
	return H;
}

int Hash(int key, int tableSize)
{
	return key%tableSize;
}

Position Find(int key, HashTable H)
{
	Position P;
	List L;
	L = H->TheLists[Hash(key, H->TableSize)];       //1.算出是哪个槽
	P = L->Next;
	while (P != NULL&&P->key != key)              //2.链表查找操作
		P = P->Next;
	return P;
}

void Insert(int key, HashTable H)
{
	Position Pos, NewCell;
	List L;

	Pos = Find(key, H);                                     //1.先找有没有在表里面
	if (Pos == NULL)
	{
		NewCell = (Position)malloc(sizeof(ListNode));       //2.没有就新建一个地址存放
		if (NewCell == NULL)
			cout << "out od space";
		else {
			L = H->TheLists[Hash(key, H->TableSize)];      //3.插入到表头和第一个元素之间
			NewCell->Next = L->Next;
			L->Next = NewCell;
			NewCell->key = key;
		}
	}
}

int main()
{
	cout << NextPrime(15);
	while (1);
    return 0;
}

  

转载于:https://www.cnblogs.com/linear/p/6635635.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值