第6.5节 自引用结构,统计输入中所有单词的出现次数

来源:互联网 发布:怎么联系网络推手 编辑:程序博客网 时间:2024/06/05 01:52

从图1可以看出用自引用结构统计输入单词的流程,结构root由NULL不断生长,程序复杂度为nlog2n




图 1. 利用自引用结构统计输入单词出现次数

已经为结构分配了内存,为什么不直接用p->word=w,而要用strdup函数将新单词复制到某个隐藏位置?分配内存是malloc的指针指向何处?此处问题留待第八章进一步学习。

        p->word=strdup(w);

书上程序:

#include <stdio.h>#include <ctype.h>#include <string.h>#define MAXWORD 100struct tnode{    char *word;    int count;    struct tnode *left;    struct tnode *right;};struct tnode *addtree(struct tnode *,char *);void treeprint(struct tnode *);int getword(char *,int);main(){    struct tnode *root;    char word[MAXWORD];    root=NULL;    while(getword(word,MAXWORD)!=EOF)        if(isalpha(word[0]))            root=addtree(root,word);    treeprint(root);    return 0;}struct tnode *talloc(void);char *strdup2(char *);struct tnode *addtree(struct tnode *p,char *w){    int cond;    if(p==NULL){        p=talloc();        p->word=strdup(w);    }else if((cond=strcmp(w,p->word))==0)        p->count++;    else if(cond<0)        p->left=addtree(p->left,w);    else        p->right=addtree(p->right,w);    return p;}void treeprint(struct tnode *p){    if(p!=NULL){        treeprint(p->left);        printf("%4d %s\n",p->count,p->word);        treeprint(p->right);    }}#include <stdlib.h>struct tnode *talloc(void){    return (struct tnode *) malloc(sizeof(struct tnode));}char *strdup2(char *s){    char *p;    p=(char *) malloc(strlen(s)+1);    if(p!=NULL)        strcpy(p,s);    return p;}int getword(char *word,int lim){    int c,d,comment(void),getch(void);    void ungetch(int);    char *w=word;    while(isspace(c=getch()))        ;    if(c!=EOF)        *w++=c;    if(isalpha(c)||c=='_'||c=='#'){        for( ;--lim>0;w++)            if(!isalnum(*w=getch())&&*w!='_'){                ungetch(*w);                break;            }    }else if(c=='\''||c=='"'){        for( ;--lim>0;w++)            if((*w=getch())=='\\')                *++w=getch();            else if(*w==c){                w++;                break;            }else if(*w==EOF)                break;    }else if(c=='/')        if((d=getch())=='*')            c=comment();        else            ungetch(d);    *w='\0';    return c;}int comment(void){    int c;    void ungetch(int);    while((c=getch())!=EOF){        if(c=='*')            if((c==getch())=='/')                break;            else                ungetch(c);    }    return c;}#define BUFSIZE 100char buf[BUFSIZE];int bufp=0;int getch(void){    return (bufp>0)? buf[--bufp]:getchar();}void ungetch(int c){    if(bufp>=BUFSIZE)        printf("ungetch: too many characters\n");    else        buf[bufp++]=c;}

strdup为库函数,发生冲突,此处改为strdup2,编译运行结果:

now is the time for all good men to come to the aid of their party^Z3539140 aid3539140 all3539140 come3539140 for3539140 good3539140 is3539140 men3549872 now3539140 of3539140 party3539141 the3539140 their3539140 time3539141 to

第40行后遗漏以下初始化语句:

        p->count=1;        p->left=p->right=NULL;
0 0
原创粉丝点击