打印文本中的所有单词,并且打印每个单词出现的行号,非实义单词不考虑(TCPL,练习6-3)

2023-02-21,,

建立一棵二叉树,每个接单存放单词以及指向一个链表的指针,以及指向左右节点的指针。链表内存放行号以及指向下一个链表节点的指针。

每录入一个单词,先寻找二叉树,再寻找它的链表,分别将单词和行号插入二叉树和链表,这样,每一个单词自然就有一个属于它的行号链表。

最后打印

代码如下:

 #include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h> #define MAXWORD 100
#define MAXHANG 10000 extern int getword(char *word, int lim);
struct hang *hes(struct hes *, int); /* 链表hang,每个节点存放行数及一个指向下一个行的指针 */
struct ci *cc(struct ci *, char *, int);/* 二叉树ci,每个节点存放一个单词以及一个指向链表hang的指针 */
void hesprint(struct hes *); /* 打印链表 */
void ccprint(struct cc *); /* 打印二叉树 */
struct hang *talloc(void); /* 为树cc申请储存空间 */
struct ci *atalloc(void); /* 为树cc申请储存空间 */
char *strduper(char *s); /* word存放在一个安全的地方 */
int exclude(char *); struct hang {
int x;
struct hang *next;
}; struct ci {
char *word;
struct hang *hangg;
struct ci *left;
struct ci *right;
}; /* 编写程序,打印文本中的所有单词,并且打印每个单词出现的行号,is,to等非实意单词不考虑 */
main() {
struct ci *root;
char word[MAXWORD];
int hangs; root=NULL; while((hangs=getword(word,MAXWORD))!=EOF) /* getword返回行号 */
if((isalpha(word[])||word[]=='_')&&!exclude(word)) /* 函数exclude确认单词是否可以被忽略 */
root=cc(root,word,hangs);
ccprint(root);
return ;
}
struct ci *cc(struct ci *p, char *w, int x) {
int cond; if(p==NULL) {
p=atalloc();
p->word=strduper(w);
p->hangg=NULL;
p->hangg=hes(p->hangg,x);
p->left=p->right=NULL; } else if ((cond= strcmp(w,p->word))==)
p->hangg=hes(p->hangg,x);
else if (cond <)
p->left=cc(p->left,w,x);
else
p->right=cc(p->right,w,x);
return p;
} struct hang *hes(struct hang *p, int x) { if(p==NULL) {
p=talloc();
p->x=x;
p->next=NULL;
} else if (p->x==x)
;
else if (p->x!=x)
p->next=hes(p->next,x);
return p; } struct hang *talloc(void) {
return (struct hang *) malloc(sizeof(struct hang)); }
struct ci *atalloc(void) {
return (struct ci *) malloc(sizeof(struct ci));
}
char *strduper(char *s) {
char *p; p=(char *)malloc(strlen(s)+);
if(p!=NULL)
strcpy(p,s);
return p;
} void hesprint(struct hang *p) {
if(p!=NULL) {
printf("%4d ",p->x);
hesprint(p->next);
}
}
void ccprint(struct ci *p) {
if(p!=NULL)
{
ccprint(p->left);
printf("%s ",p->word);
hesprint(p->hangg);
printf("\n");
ccprint(p->right);
} } int exclude(char *s) {
static char *ex[]={
"a",
"an",
"and",
"are",
"in",
"is",
"of",
"or",
"that",
"the",
"this",
"to"
};
int cond,mid;
int low=;
int high=sizeof(ex)/sizeof(char *)-; while(low<=high) {
mid=(low+high)/;
if((cond=strcmp(s,ex[mid]))==)
return ;
else if(cond<)
high=mid-; else if(cond>)
low=mid+; }
return ;
}

打印文本中的所有单词,并且打印每个单词出现的行号,非实义单词不考虑(TCPL,练习6-3)的相关教程结束。

《打印文本中的所有单词,并且打印每个单词出现的行号,非实义单词不考虑(TCPL,练习6-3).doc》

下载本文的Word格式文档,以方便收藏与打印。