题目描述
采用除留余数法(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<cstring> #include<string> #include<cstdio> using namespace std; #define INF 0x3f3f3f3f #define M 100 typedef struct node { int data; struct node*next; }LNode; typedef struct { LNode*firstp; }hashtable; void inserthash(hashtable ha[],int m,int num) { int temp=num%m; LNode*q=(LNode*)malloc(sizeof(LNode)); LNode*r; q->next=NULL; q->data=num; if(ha[temp].firstp==NULL) { ha[temp].firstp=q; } else { r=ha[temp].firstp; while(r->next!=NULL) { r=r->next; } r->next=q; } } void createhash(hashtable ha[],int n,int m,int key[]) { for(int i=0;i<m;i++) { ha[i].firstp=NULL; } for(int i=0;i<n;i++) { inserthash(ha,m,key[i]); } } void search(hashtable ha[],int n,int m,int k) { int i=0; int temp=k%m; LNode*q=ha[temp].firstp; while(q!=NULL) { i++; if(q->data==k) { break; } q=q->next; } if(q!=NULL) { cout<<k%m<<","<<i; } else { cout<<"-1"; } } int main() { hashtable ha[M]; int m,n; cin>>m>>n; int key[M]; for(int i=0;i<n;i++) { cin>>key[i]; } int k; cin>>k; createhash(ha,n,m,key); search(ha,n,m,k); return 0; }
SWUST OJ1012: 哈希表(链地址法处理冲突)
最新推荐文章于 2023-06-28 22:26:39 发布