現状、それぞれの単語が何回出現しているかは、ハッシュ表に登録するところまではできています。
ただ、ソートをすることができていません。実行してもエラーは出ないのですが、結果が表示されません。
どこまでプログラムが動いているのか確認したところ、ソート処理を行う前までは正常に動いているようです。
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define WORDLEN 50
#define MAXCOUNT 2500
#define SIZE 32
struct wd {
struct wd *next;
char *str;
int count;
};
typedef struct wd WORD;
WORD *word[SIZE];
WORD *s_word[MAXCOUNT];
void init_word();
void init_s_word();
WORD *add_word(char *);
char *getword(char *, int);
int main()
{
char w[WORDLEN];
WORD *p,*q;
int i,j;
init_word();
init_s_word();
while (getword(w, WORDLEN) != NULL) {
p = add_word(w);
if (p == NULL) {
fprintf(stderr, "Too many words\n");
exit(1);
}
p->count++;
}
printf("\n");
//ここから下の部分でソートしようとしている
for(j=0;j<SIZE;j++){
for(q=word[j];q!=NULL;q=q->next){
s_word[q->count]=q;
s_word[q->count]->next = (WORD *)malloc(sizeof(WORD));
s_word[q->count]=s_word[q->count]->next;
}
}
printf("\n");
for (i = 1; i < MAXCOUNT; i++) {
for (p = s_word[i]; p != NULL; p = p->next) {
printf("%d %s\n", p->count, p->str);
}
}
return 0;
}
void init_word()
{
int i;
for (i = 0; i < SIZE; i++)
word[i] = NULL;
}
void init_s_word(){
int i;
for(i=0;i<MAXCOUNT;i++)
s_word[i]=NULL;
}
int hash(char *w){
int i;
unsigned int h=0;
for(i=0;w[i]!='\0';i++)h=65599*h+w[i];
return h % SIZE;
}
WORD *add_word(char *w)
{
char *s;
WORD *p;
int i;
i = hash(w);
for (p = word[i]; p != NULL; p = p->next) {
if (strcmp(w, p->str) == 0)
return p;
}
s = (char *)malloc(strlen(w) + 1);
if (s == NULL)
return NULL;
strcpy(s, w);
p = (WORD *)malloc(sizeof(WORD));
if (p == NULL)
return NULL;
p->str = s;
p->count = 0;
p->next = word[i];
word[i] = p;
return p;
}
char *getword(char *w, int n)
{
int c;
int i = 0;
if (n <= 0 || feof(stdin))
return NULL;
c = getchar();
while (c != EOF && ! isalpha(c)) {
c = getchar();
}
if (c == EOF)
return NULL;
while (isalpha(c)) {
if (i < n - 1)
w[i++] = toupper(c);
c = getchar();
}
if (i < n)
w[i++] = '\0';
return w;
}