相對比較低效的解決方式
更好的方式推薦用字典樹
#include?<stdio.h>#include?<stdlib.h>
#include?<string.h>
struct?node;
typedef?struct?node?NODE,?*pNode;
struct?node{
char?*str;
int?times;
pNode?next;
};
pNode?new_node(char?*str)
{
pNode?p;
p?=?malloc(sizeof(NODE));
p->str?=?malloc(strlen(str)?+?1);
strcpy(p->str,?str);
p->times?=?1;
p->next?=?NULL;
return?p;
}
pNode?find_str(pNode?head,?char?*str)
{
pNode?p;
p?=?head;
while(p)
{
if(strcmp(p->str,?str)?==?0)
break;
p?=?p->next;
}
return?p;
}
void?insert_node(pNode*?head,?pNode?n)
{
pNode?last?=?NULL,?cur;
cur?=?*head;
while(cur)
{
if(strcmp(cur->str,?n->str)?>?0)break;
last?=?cur;
cur?=?cur->next;
}
if(last?==?NULL)?
{
n->next?=?cur;
*head?=?n;
}
else
{
n->next=last->next;
last->next?=?n;
}
}
void?print_list(pNode?head)
{
pNode?p?=?head;
while(p)
{
printf("%s?%d\n",?p->str,?p->times);
p?=?p->next;
}
}
void?delete_list(pNode?head)
{
pNode?p?=?head;
if(p->next)?delete_list(p->next);
free(p->str);
free(p);
}
int?main()
{
int?c;
char?word[1024];
pNode?head?=?NULL;
int?j?=?0;
int?words=?0,?cnt=0;
while(1)
{
c?=?getchar();
if(c?!=?'?'?&&?c?!=?'\n')
word[j++]?=?c;
else
{
if(j)
{
pNode?t;
word[j]?=?0;
t?=?find_str(head,?word);
if(t)?t->times?++;
else
{
t?=?new_node(word);
if(head)
insert_node(&head,?t);
else?head?=?t;
words?++;
}
cnt?++;
j?=?0;
}
}
if(c?==?EOF)?break;
}
printf("Words:%d?Counts:%d\n",?words,?cnt);
print_list(head);
delete_list(head);
return?0;
}