【发布时间】:2014-12-23 13:34:10
【问题描述】:
我想为我必须在我的大学发送的练习创建一个哈希表。
该程序将打开多个文件,将每个文件的内容分解为<<words>>(令牌),并将每个<<word>> 以每个<<word>> 的频率保存在一个哈希表中。
如果单词已经在哈希表中,程序会增加单词的频率。
最后,程序将相应地打印单词及其频率。
此外,频率应从最高词频到最低词频打印。
<<words>> 的比较将忽略大小写字母。
例如,如果文件包含:one two three four Two Three Four THREE FOUR FoUr
它应该打印:
四个4
三 3
两个 2
一个 1
教授给了我们一个我们应该完成的模板,但我真的很困惑如何处理 insert_ht() 和 clear_ht() 函数以及比较函数。
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define HTABLE_SIZ 1001
#define MAX_LINE_SIZ 1024
/* Hash Table */
typedef struct node* link;
struct node { char *token; int freq; link next; };
link htable[HTABLE_SIZ] = { NULL }; /* Table of lists (#buckets) */
int size = 0; /* Size (number of elements) of hash table */
unsigned int hash (char *tok );
void insert_ht (char *data);
void clear_ht ( );
void print_ht ( );
void Process(FILE *fp);
int main(int argc, char *argv[])
{
int i;
FILE *fp;
for (i=1; i < argc; i++)
{
fp = fopen(argv[i],"r");
if (NULL == fp)
{
fprintf(stderr,"Problem opening file: %s\n",argv[i]);
continue;
}
Process(fp);
fclose(fp);
}
print_ht();
clear_ht();
return 0;
}
void Process(FILE *fp)
{
const char *seperators = " ?!'\";,.:+-*&%(){}[]<>\\\t\n";
char line[MAX_LINE_SIZ];
char *s;
while((fgets(line,MAX_LINE_SIZ, fp)) != NULL)
{
for (s=strtok(line,seperators); s; s=strtok(NULL,seperators))
insert_ht(s);
}
}
/* Hash Function */
unsigned int hash(char *tok)
{
unsigned int hv = 0;
while (*tok)
hv = (hv << 4) | toupper(*tok++);
return hv % HTABLE_SIZ;
}
void insert_ht(char *token)
{
……………………………………………
}
void clear_ht()
{
……………………………………………
}
int compare(const void *elem1, const void *elem2)
{
……………………………………………
}
void print_ht()
{
int i, j=0;
link l, *vector = (link*) malloc(sizeof(link)*size);
for (i=0; i < HTABLE_SIZ; i++)
for (l=htable[i]; l; l=l->next)
vector[j++] = l;
qsort(vector,size,sizeof(link),compare);
for (i=0; i < size; i++)
printf("%-50s\t%7d\n",vector[i]->token,vector[i]->freq);
free(vector);
}
【问题讨论】:
-
标准警告:请do not cast
malloc()的返回值。 -
还没到编译步骤。试图找出程序中的主要功能。不过感谢您的提示:)
标签: c hashtable frequency words