算法题:读入一篇英文文章,统计其中的单词,并得到每个单词出现的次数

// 读入一篇英文文章,统计其中的单词,并得到每个单词出现的次数
// 链表的应用
//================================================================

#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;  
}

  

posted @ 2017-06-19 19:19  弗莱曼飞侠  阅读(2330)  评论(0编辑  收藏  举报