c++中的哈希算法实现

/*
	哈希算法的实现原理是:
		通过获得你要排序的序列长度(m),
		然后得出比这个 m 大的素数作为数组的长度(n),
		然后对接下来的输入数据(D)进行取模运算(v=D%n),
		然后取模之后的数据存到数组中。
		但是这样做会出现当个取模之后余数相同的情况 
		我这里介绍常用的解决方法  拉链哈希 : 
		拉链哈希 就是先进行哈希,但是在存储的时候使用链表。
		这样做的弊端是,当取模之后的余数相同的情况特别严重的时候会容易出现最坏的情况
		这时候你可以做的就是更改 n 值或者采用其他的解决方案,但是推荐采取更改 n 值 
		 
*/
#include 
using namespace std;

typedef int Elm;
#define Mod  7;

struct nds
{
	Elm data;
	nds* next;
};
struct L
{
	int num;//标志这个链表的元素个数 
	nds *first; 
};
L[Mod];
void haxi_create(Elm *p,int n)
{
	int k=0;Elm r;nds *s,*h;
	while(kdata=p[k];
		s->next=NULL;
		if(L[r]->first==NULL) L[r]->first=s;
		else 
		{
			h=L[r]->first;
			while(h->next) h=h->next;
			h->next=s;
		}
	}
}
int haxi_find(Elm e)
{
	Elm b=E%Mod;
	bool flage=false;	
	nds*o=L[b]->first;
	if(!o) return -1;
	while(o)
	{
		if(o->data==e) 
		{
			flage=true;
			break; 
		}
		o=o->next;
	}
	if(flage) return 1;
	else return -1;
}

猜你喜欢

转载自blog.csdn.net/play_841266670/article/details/73011842