该算法实现了字符串数组的词频统计以及查找:
// 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();
}