word_fre.cpp

来自「计算机科班学生的词法分析作业」· C++ 代码 · 共 70 行

CPP
70
字号
# include <stdio.h>
# include <string.h>
# include <malloc.h>
# define   LEN   sizeof(struct wordfrq)
# define   NULL  0
# define   MAX   1000
/*define a struct to save the data:words and their frequency*/
struct wordfrq 
{
	char word[MAX];
	int frequency;
	struct wordfrq * next;
};
/*order the words by their frequency from big to small and change the LianBiao*/
void insert(struct wordfrq *head, struct wordfrq *nod)
{
	struct wordfrq *p=head->next,*q=head;
	while(p && p->frequency>nod->frequency)
	{
		p=p->next;
		q=q->next;
	}
	q->next=nod;
	nod->next=p;
}
/*check the words entered(either exist or not),make their frequency 
  changed and print the all words existed and their frequency*/ 
void check(struct wordfrq *head,char st[])
{
	struct wordfrq *m,*p;
	p=head;
	m=head->next;
	while(m && strcmp(m->word,st)!=0)
	{
		p=m;
		m=m->next;
	}
	if(m==NULL)
	{
		m=(struct wordfrq *)malloc(LEN);
		m->frequency=1;
		strcpy(m->word,st);
	}
	else
	{
		p->next=m->next;
		m->frequency++;
	}
	insert(head,m);
	for(m=head->next; m; m=m->next)
		printf("%s:%d ",m->word,m->frequency);
	putchar('\n');
}
void main(  )
{
	char st[MAX];
	/*creat a head of a LianBiao so that the data check and insert can be less easy*/
	struct wordfrq *head=(struct wordfrq *)malloc(LEN);
	head->next=NULL;
	/*tell the user to enter the data and get them*/
	printf("Please enter the numbers:\n");
	scanf("%s",st);
	/*if the char get from the user is not a signal for exit,make the change ,else eixt*/
	while(strcmp(st,"#")!=0)
	{
		check(head,st);
		scanf("%s",st);
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?