// 读入一篇英文文章,统计其中的单词,并得到每个单词出现的次数
// 链表的应用 AC
#include <cstring>
#include <cstdio>
#include <cstdlib>
typedef struct _link{
char* ch;
int num;
_link* next;
}link;
int main(int argc,char* argv[]){
FILE *fp;
fp = fopen("test0001.txt","r");
char word[1025];
int pos = 0;
char c;
link *head,*pnow,*ptmp;
head = pnow = ptmp = NULL;
while(!feof(fp)){
c = fgetc(fp);
if( (c>='a' && c<='z') || (c>='A' && c<= 'Z') || c=='\'' ){
word[pos++] = c;
}else if(pos>0){
word[pos] = '\0';
//链表遍历,比较链表中的结点值与单词值
ptmp = head;
while(ptmp){
if(strcmp(word,ptmp->ch) == 0){
ptmp->num++;
break;
}
ptmp = ptmp->next;
}
//如果链表中没有当前的单词,在链表末尾插入结点
if(ptmp== NULL){
ptmp = (link*)malloc(sizeof(link));
ptmp->ch = (char*)malloc(pos);
strcpy(ptmp->ch,word);
ptmp->num = 1;
ptmp->next = NULL;
if(pnow){ //当前插入结点为末结点
pnow->next = ptmp;
pnow = ptmp;
}else{ //此处为第一次出现单词的时候
head = pnow = ptmp;
}
}
pos = 0;
}
}
fclose(fp);
ptmp = head;
FILE *fp1 = fopen("test0002.txt","w");
while (ptmp){
fprintf(fp1,"%d\t%s\n",ptmp->num,ptmp->ch);
printf("%d-%s\n",ptmp->num,ptmp->ch);
ptmp = ptmp->next;
}
fclose(fp1);
return 0;
}