使用单链表统计英文文本单词个数

#include "stdio.h" 
#include "malloc.h"
#include "string.h"
/**
*		因为扫描的过程需要往线性表中增加数据,所以使用单链表的形式,减少移动 
*		
*		注意下面三个*********************************************中的内容
* 		都是容易出错的地方! 
*/ 

//统计字符串中单词个数及每个单词出现次数
typedef struct WordsNode{
	int time;
	char s[20];//单词,最长长度为20 
	WordsNode *next; 
}WList; 

	
//将单词插入到带头节点的递增顺序排列的单链表中 
WList *function(char word[],WList *list){
	WordsNode *p=list->next,*pre=list;;
	while(p&&strcmp(p->s,word)<0){
		pre=p;
		p=p->next;
	}
	if(p==NULL || strcmp(p->s,word)){
		WordsNode *node=(WList *)malloc(sizeof (WordsNode));
		node->time=1;
		strcpy(node->s,word);//***********字符串不能直接赋值,需要拷贝或者手动遍历赋值!!!*************** 
		node->next=pre->next;
		pre->next=node;
	}else if(strcmp(p->s,word)==0){
		p->time=p->time+1;
	}
	return list; 
}

//扫面文章字符串,生成递增的单链表 
WList *create(char *text){
	WList *list=(WList *)malloc(sizeof (WordsNode));//头结点 
	list->next=0;
	int i=0,j=0;
	char c=text[i];
	char word[20];
	while(c!='\0'){
		if((c>='A'&&c<='Z') || c>='a'&&c<='z'){
			word[j]=c;
			j++;
		}else{
			if(j>0){
				word[j]='\0';//******************字符结束标志!!!************************
				list=function(word,list);
				j=0;
			}
		}
		i++;//***************************不要忘记递增!!!最好循环开始的时候就写好********************************* 
		c=text[i];	
	}
	return list;
}

void print(WList *list){
	WordsNode *p=list->next;
	while(p) {
		printf("%10s	:%10d次\n",p->s,p->time);
		p=p->next;
	}
}

int main(){
	char s[300]="If the public can be well educated to enhance their awareness over the benefits of promoting Chinese culture | preserving the living circumstance | promoting the phenomenon mentioned, it would be much better.";
	WList *list=create(s);
	print(list);
}


  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值