// 讀入一篇英文文章,統計其中的單詞,並得到每個單詞出現的次數
// 鏈表的應用
//================================================================
#include <string.h>
#include <malloc.h>
typedef struct _link // 定義該鏈表是為了存儲不重復出現的單詞
{
char* ch;
int num;
_link* next;
}link;
int main(int argc, char* argv[])
{
// 讀入一個txt.文件操作
FILE *fp;
fp = fopen("test1.txt","r");
char word[1025];
int pos = 0; // 亦可用 size_t類型
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("result.txt","w");
while (ptmp)
{
fprintf(fp1,"%d\t%s\n", ptmp->num, ptmp->ch);
ptmp = ptmp->next;
}
fclose(fp1);
return 0;
}
