#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
typedef struct List {//链表
struct List *next;
}List;
typedef struct WordList { //单词结构
List *next;
char *word;
int count;
}WordList;
static WordList *createWordList(char *word);
static WordList *addWordList(WordList *list, char *word);
static void freeWordList(WordList *list);
static void printWordList(WordList *list);
static void sortWordList(WordList *list);
static int getword(char *word) { //按单词 ,读取文件
if (word == NULL)
return -1;
char c;
int count = 0;//记录读取数量
while (isspace(c = getchar())) //跳过空字符
;
if (c == EOF)
return EOF;
if (!isalpha(c)) { //判断第一个字符,是否是字母字符,如果不是则表示不是一个单词,跳过
while (!(isspace(c = getchar())) && c != EOF)//直到下个空字符结束
;
if (c == EOF)
return EOF;
return 0;
}
if (isalpha(c)) { //读取单词
word[count++] = c;
while (isalpha(c = getchar()) && c != EOF && (word[count++] = c))//读取连续的字母
;
word[count] = '\0';
if (c == EOF)
ungetc(c, stdin);
}
return count;
}
int main() {
WordList *list = NULL;
char buf[128];
int ret;
while ((ret=getword(buf)) != EOF) {
if (ret>0)
{
list = addWordList(list, buf);
}
}
sortWordList(list);
printWordList(list);
freeWordList(list);
system("pause");
return 0;
}
static WordList *createWordList(char *word) {//创建一个节点
if (word == NULL)
return NULL;
WordList *list = (WordList*)calloc(1, sizeof(WordList));
list->word = strdup(word);
list->count = 1;
return list;
}
static WordList *addWordList(WordList *list, char *word) {//递归查找,并添加添加节点
if (list == NULL) {//当前节点是空 则创建节点
return createWordList(word);
}
else if (strcmp(list->word, word) == 0) {//如果有当前单词,
++list->count; //计数器加1
}
else
{ //否则递归下一个节点
if (list->next)
addWordList(list->next, word);
else
list->next = addWordList(list->next, word);
}
return list;
}
static void freeWordList(WordList *list) {//释放节点
if (list == NULL)
return;
free(list->word);//释放当前单词空间
freeWordList(list->next);//递归下一个节点
free(list);//释放自己
}
static void printWordList(WordList *list) {
if (list == NULL)
return;
printf("次数:%d 单词:%s\n", (WordList*)list->count, (WordList*)list->word);
printWordList(list->next);
}
static void sortWordList(WordList *list) { //排序
WordList *t1, *t2, *temp;
temp = (WordList*)calloc(1, sizeof(WordList));
for (t1 = list;t1->next != NULL;t1 = (WordList*)t1->next) {
for (t2 = (WordList*)t1->next;t2->next != NULL;t2 = (WordList*)t2->next) {
if (t1->count < t2->count) {
temp->word = t1->word;
temp->count = t1->count;
t1->word = t2->word;
t1->count = t2->count;
t2->word = temp->word;
t2->count = temp->count;
}
}
free(temp);
}