您的位置:首页 > 其它

链地址法+动态开辟内存 hash

2015-05-29 22:38 471 查看
链地址法 (一)

自我感觉链地址法是hash的最简单易懂的方法,于是就在课下实现了一下

它的特点是能够较直观的解决冲突问题

但是同样,它也有缺点,那就是每次查询时都要遍历某个头结点后面的所有结点

如图示





因此优化方法是
1:尽可能的使用素数作为mod的对象

2:mod的对象足够大
这样可以使数字排列的更散乱,以减少冲突

要求输入n个数,查询m次,

代码如下

<strong>#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
struct node
{
int x;
node *next;
//    node()
//    {
//        next=NULL;
//    }
};

int n,m;

const int mod=99997;
node *str[mod];

void hasha(int a)
{
int b=a;
a=a%mod;
node *q=str[a];
while(q->next)
{
q=q -> next;
}//new (node);
node *p=(node*) malloc (sizeof(node));
p->next=NULL;
p->x=b;
q->next=p;
return;
}
int main()
{
for(int i=0; i<mod; i++)
{
// str[i]=new(node);
str[i]=(node*) malloc (sizeof(node));
str[i]->next=NULL;
}
node *p=NULL;
int aa;
scanf("%d%d",&n,&m);
while(n--)//输入n个数
{
scanf("%d",&aa);
hasha(aa);
}
while(m--)//查询n次
{
scanf("%d",&aa);
int bb=aa;
aa=aa%mod;
p=str[aa];
int flog=0;
while(p->next)
{
p=p->next;
if(bb==p->x)
{
flog=1;
break;
}

}
if( flog == 0 )
printf("NO\n");
else
printf("YES\n");
}
}
</strong>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: