自己实现拉链法哈希表

 1 #include<bits/stdc++.h>
 2 #define mytest
 3 using namespace std;
 4 const int N=1e5+5;
 5 const int mod=1337;
 6 int h[N];//h[i]表示key为i的开头节点编号
 7 int tot;
 8 struct edge//链式前向星存节点 e[i]表示第i个节点的编号
 9 {
10     int val,next;//节点内存的是当前节点的value和下一个节点的编号;
11 }e[N];
12 void addedge(int key,int val)
13 {
14     key%=mod;
15     e[tot]=(edge){val,h[key]};
16     h[key]=tot++;
17 }
18 int findhash(int key,int info)
19 {
20     key%=mod;
21     for(int i=h[key];~i;i=e[i].next)
22     {
23         if(e[i].val==info)return 1;
24     }
25     return 0;
26 }
27 int main()
28 {
29     #ifdef mytest//如果定义了mydest宏就执行直到endif;没有就跳过这段 
30     freopen("in.txt","r",stdin);
31     freopen("out.txt","w",stdout);
32     cout<<"great!"<<endl;
33     #endif 
34     memset(h,-1,sizeof(h));
35     for(int i=1;i<=11;i++)
36     {
37         int x;
38         scanf("%d",&x);
39         addedge(x,x);
40     }
41     //addedge(1338,1338);
42     for(int i=1;i<=10;i++)cout<<findhash(i,i)<<" "<<i<<endl;
43     cout<<findhash(1338,1338)<<endl;
44     cout<<findhash(1337,1337)<<endl;
45     return 0;
46  } 

 

 

posted @ 2021-12-08 21:36  matt-11  阅读(77)  评论(0)    收藏  举报