c 程序设计语言 第二版 练习题 6-4

来源:互联网 发布:mac怎么iphone铃声 编辑:程序博客网 时间:2024/05/18 04:46
#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);elselist->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);}

0 0
原创粉丝点击