swust oj 1012

时间:2023-03-09 10:07:21
swust oj 1012

哈希表(链地址法处理冲突)

1000(ms)
10000(kb)
2542 / 6517
采用除留余数法(H(key)=key %n)建立长度为n的哈希表,处理冲突用链地址法。建立链表的时候采用尾插法。

输入

第一行为哈西表的长度m;
第二行为关键字的个数n;
第三行为关键字集合;
第四行为要查找的数据。

输出

如果查找成功,输出该关键字所在哈希表中的地址和比较次数;如果查找不成功,输出-1。

样例输入

13
13
16 74 60 43 54 90 46 31 29 88 77 78 79
16

样例输出

3,1
 #include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<list>
#define rep(i,a,b) for(int i=a;i<b;i++)
using namespace std;
typedef int KeyType;
typedef struct node
{
KeyType key;
struct node *next;
}NodeType;
typedef struct{
NodeType *firstp;
}HashTable; void InsertHT(HashTable ha[],int &n,int p,KeyType k)
{
int adr;
adr=k%p;
NodeType *q,*r;
q=(NodeType *)malloc(sizeof(NodeType));
q->next=NULL;
q->key=k;
if(ha[adr].firstp==NULL)
ha[adr].firstp=q;
else
{
r=ha[adr].firstp;
while(r->next!=NULL)
{
r=r->next;
}
r->next=q;
}
n++;
} void creatHT(HashTable ha[],int &n,int m,int p,KeyType keys[],int nl)
{
rep(i,,m)
ha[i].firstp=NULL;
n=;
rep(i,,nl)
InsertHT(ha,n,p,keys[i]);
} bool DeleteHT(HashTable ha[],int &n,int m,int p,KeyType k)
{
int adr;
adr=k%p;
NodeType *q,*preq;
q=ha[adr].firstp;
if(q==NULL)
return false;
if(q->key==k)
{
ha[adr].firstp=q->next;
free(q);
n--;
return true;
}
preq=q;
q=q->next;
while(q!=NULL)
{
if(q->key==k)
break;
q=q->next;
}
if(q!=NULL)
{
preq->next=q->next;
free(q);
n--;
return true;
}
else
return false;
} void serchHT(HashTable ha[],int p,KeyType k)
{
int i=,adr;
adr=k%p;
NodeType *q;
q=ha[adr].firstp;
while(q!=NULL)
{
i++;
if(q->key==k)
break;
q=q->next;
}
if(q!=NULL)
cout<<k%p<<","<<i;
else
cout<<"-1";
} int main()
{
int m,n,k,x;
KeyType keys[];
HashTable ha[];
cin>>m>>n;
rep(i,,n)
cin>>keys[i];
cin>>k;
creatHT(ha,x,m,m,keys,n);
serchHT(ha,m,k);
rep(i,,n)
DeleteHT(ha,x,m,m,keys[i]);
return ;
}