自己写的hash

本文介绍了一种基于哈希表的数据结构实现方法,并通过示例代码详细解释了如何使用哈希表进行数据的存储与查找操作。文章还提供了一个具体的实例来演示哈希表的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;

#define HASH 359987 
typedef struct node
{
  char str[22]; 
  int key;
  struct node *next;      
};
node *h[HASH];

int hashcode(char str[])
{
  int hash=0;
  int len = strlen(str);
  for(int i=0;i<len;i++)
  hash =(31*hash+str[i])%HASH;
  return hash;    
}

void create(char str[],int x)
{
  int hash = hashcode(str);
  node *tmp =new node;
  tmp->key=x;
  strcpy(tmp->str,str);
  tmp->next=h[hash];
  h[hash]=tmp;
  return ;   
}

int find(char str[])
{
    int hash = hashcode(str);
    node *tmp = h[hash];
    while(tmp!=NULL)
    {
      // printf("%s\n",tmp->str);             
       if(strcmp(tmp->str,str)==0)
       return tmp->key;
       tmp=tmp->next;             
    }
  return -1;     
}


int main()
{
    int n,m,i,x;
    char str[22];
    while(scanf("%d%d",&n,&m)!=EOF)
    {
         memset(h,0,sizeof(h));
       for(i=0;i<n;i++)
       {
         scanf("%s %d",&str,&x);  
         create(str,x);  
       }
       while(m--)
       {
         scanf("%s",&str);    
         printf("%d\n",find(str));     
       }
                                      
                                   
    }
    
    
return 0;    
}

/*

20 10
IG 3500
WE 4000
Fnatic 3900
GG 3950
EG 3700
SK 3750
TSM 3750
VUL 3850
CLG 3800
TPA 3700
PE 3600
HZ 3500
froggen 2300
alex 2161
kid 2132
weixiao 2382
WEcm 2310
IGpdd 2131
fzzf 2344
xiaoxiao 2012
IG
WE
SK
HZ
fzzf
froggen
alex
WE
qq
WEcm

*/


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值