70,022
社区成员




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned int BKDRHash(char *str);
typedef char *KeyType;
typedef struct{
KeyType key;
int count;
}ElemType;
typedef struct{
ElemType *elem;
unsigned int size;
unsigned int real_size;
}HashTable;
void error_and_die(const char *msg){
perror(msg);
exit(EXIT_FAILURE);
}
unsigned int BKDRHash(char *str){
unsigned int seed = 31; // 31 131 1313 13131 131313 etc..
unsigned int hash = 0;
unsigned int i = 0;
while (*(str+i)) {
hash = (hash * seed + (*str+i)) ;
i++;
}
return hash;
}
unsigned int insert_hash(HashTable *ht,char *key){
unsigned int collision_num=0;
unsigned int p=BKDRHash(key)%ht->size;;
while(ht->elem[p].key!=NULL && strcmp(ht->elem[p].key,key)!=0){
collision_num++;
if(collision_num==(ht->size-ht->real_size)) return -1;
//平方探测法,f(i)=i^2=f(i-1)+2i-1
p+=2*collision_num-1;
if(p>ht->size) p-=ht->size;
}
if(ht->elem[p].key==NULL){
//ht->elem[p].key=strdup(key);
ht->elem[p].key=calloc(sizeof(char),(strlen(key)+1));
strcpy(ht->elem[p].key,key);
ht->elem[p].count=1;
ht->real_size++;
}else if(strcmp(ht->elem[p].key,key)==0){
ht->elem[p].count++;
}
return collision_num;
}
unsigned int insert_hash_with_count(HashTable *ht,char *key,int count){
unsigned int collision_num=0;
unsigned int p=BKDRHash(key)%ht->size;;
while(ht->elem[p].key!=NULL && strcmp(ht->elem[p].key,key)!=0){
collision_num++;
p+=2*collision_num-1;
}
//ht->elem[p].key=strdup(key);
ht->elem[p].key=calloc(sizeof(char),(strlen(key)+1));
strcpy(ht->elem[p].key,key);
//free(key);
ht->elem[p].count=count;
ht->real_size++;
return collision_num;
}
void init_hash(HashTable *ht,int size){
ht->size=size;
ht->elem=malloc(sizeof(ElemType)*ht->size);
ht->real_size=0;
}
void recreate_hash(HashTable *ht,int size){
ElemType *tmp=ht->elem;
unsigned int old_size=ht->size;
init_hash(ht,size);
unsigned int i=0;
for(i=0;i<old_size;i++){
if(tmp[i].key!=NULL)
{
insert_hash_with_count(ht,tmp[i].key,tmp[i].count);
free(tmp[i].key);
}
}
free(tmp);
}
int main(int argc, char *argv[]){
unsigned int hashsize[]={5,101,100057,2000003,10000019,20000047,100000007};
HashTable *ht=malloc(sizeof(HashTable));
int step=0;
init_hash(ht,hashsize[step]);
int i=0;
char line[8192];
int p;
while(fgets(line,8092,stdin)){
line[strlen(line)-1]='\0';
if(ht->real_size > (int)ht->size*0.75){
recreate_hash(ht,hashsize[++step]);
p=insert_hash(ht,line);
continue;
}
int p=insert_hash(ht,line);
if(p==-1){
recreate_hash(ht,hashsize[++step]);
p=insert_hash(ht,line);
}
}
for(i=0;i<ht->size;i++)
{
if(ht->elem[i].key!=NULL)
printf("%s\t%d\n",ht->elem[i].key,ht->elem[i].count);
free(ht->elem[i].key);
}
free(ht->elem);
free(ht);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NULLKEY NULL
typedef struct{
unsigned int BKDRHash(char *str);
typedef char KeyType[8192];
typedef struct{
KeyType key;
int count;
#include <stdio.h>