简单的哈希表实现

该算法实现了字符串数组的词频统计以及查找:

// hashtable.cpp : 定义控制台应用程序的入口点。

//
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#define  max  40
typedef struct  hash_node{
const char* str;
int frquency;
struct hash_node *next;


}hash_node;




typedef struct hash_table_node{
struct hash_node *next;
}hash_table_node;




hash_table_node ht[max];




void hash_init()
{
int i=0;
for (;i<max;i++)
{
ht[i].next=NULL;
}
}


/************************************************************************/
/* BKDR 算法求字符串hash值                                                                     */
/************************************************************************/
unsigned int gethashcode(const char* s)
{
int len=strlen(s);
int key=0;
for (int i=0;i<len;i++)
{
key =key*31+s[i];
}
return key%max;
}


/*
#define  hash_insert(unsigned int key,struct hash_node * node ) \
node->next=ht[key].next; \
ht[key].next=node;
*/


void hash_insert(unsigned int key,struct hash_node * node) 
{
node->next=ht[key].next;
ht[key].next=node;
}


int checkandmodify(unsigned int key ,const char* s)
{
struct hash_node *temp=ht[key].next;
while (temp!=NULL)
{
if (!strcmp(s,temp->str))
{
temp->frquency++;
return 1;
}
temp=temp->next;
}
return 0;
}


void display()
{
for (int i=0;i<max;i++)
{
printf("[%d]:",i);
struct hash_node *temp=ht[i].next;
while (temp!=NULL)
{
printf("str=%s,frequency=%d;",temp->str,temp->frquency);
temp=temp->next;
}
printf("\n");
}
}




void main()
{
char s[20];
struct hash_node *temp;
hash_init();
printf("begin to construct hash table\n please input charsets ended by ## \n");
scanf("%s",s);
while (strcmp(s,"##"))
{
int key=gethashcode(s);
int ret=checkandmodify(key,s);
if (ret==0)
{
temp=(struct hash_node*)malloc(sizeof(struct hash_node));
temp->frquency=1;
char *str=(char *)malloc(sizeof(strlen(s)+1));
strcpy(str,s);
temp->str=str;
hash_insert(key,temp);
}
scanf("%s",s);
}
display();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值