使用二叉樹對單詞進行查找

好程序員訓練營

<A href="http://www.goodprogrammer.org/" target="blank">ios培訓</A>

------我的c語言筆記,期待與您交流! 

#include<stdio.h>

#include<stdlib>

#include<ctype.h>

#include<string.h>

#define BUFSIZE 100

#define MAXWORD 100


char buf[BUFSIZE];

int bufp=0;

struct tnode *talloc(void);

char *strdup(char *);//函數聲明,同時需要函數的定義

struct tnode *addtree(struct tnode *,char *);

void treeprint(struct tnode *);

int getword(char *,int);


struct tnode

{

    char *word;

    int count;

    struct tnode *left;

    struct tnode *right;

};


/*取回一個字符(可能是壓回的字符)*/

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;

}


/*getword函數:從輸入中讀取下一個單詞或字符*/

int getword(char *word,int lim)

{

    int c,getch(void);

    void ungetch(int);

    char *w=word;


    while(isspace(c=getch()));

       if(c!=EOF)

          *w++=c;

  if(!isalpha(c))

  {

      *w='\0';

      return c;

  }

  for(;--lim>0;w++)

     if(!isalnum(*w=getch()))

     {

         ungetch(*w);

 break;

     }

  *w='\0';

    return word[0];

}


/*addtree函數:在P的位置或p的下方增加一個w節點*/

struct tnode *addtree(struct tnode *p, char *w)

{

    int cond;


    if(p==NULL)

    {

p=talloc();

p->word=strdup(w);

p->count=1;

p->left=p->right=NULL;

    }

    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;


/*strdup函數:複製s到某個位置*/

char *strdup(char *s)

{

    char *p;


    p=(char *) malloc(strlen(s)+1);

    if(p!=NULL)

strcpy(p,s);

    return p;

}


/*talloc函數:創建一個tnode */

struct tnode *talloc(void)

{

    return (struct tnode *) malloc(sizeof(struct tnode));

}


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;














發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章