测试博客

测试

北航 机试 文章识别 二插搜索树

题目

描述:输入一篇可能未经排版的文章,挑选出其中的单词【单词中不包含“(”等特殊符号】,然后按字典序输出。
输入:从文件中读取文章
输出:按字典序输出单词
样例:
输入
When most kids go to school and study the knowledge, few special kids have made their history. A small boy from America wins the international contest by defeating adult competitors. He becomes the youngest winner. He has the gift and so many parents want to have such a kid. Though we are not that smart, we still can study hard to realize our dreams.
输出
a
adult
america
and
are
becomes
boy
by
can
competitors
contest
defeating
dreams
few
rom
gift
go
hard
has
have
he
history
international
kid
kids
knowledge
made
many
most
not
our
p
rents
realize
school
small
smart
so
special
still
study
such
that
the
their
though
to
want
we
when
winner
wins
youngest

代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

typedef struct Node{
    char w[50];
    struct Node* parent;
    struct Node* lchild;
    struct Node* rchild;
}BTree;

void binary_insert(BTree* T,BTree* w){
    BTree* y =NULL;
    BTree* x = T->lchild;

    int res = 0;
    while(x!=NULL){
        y = x;
        res = strcmp(w->w,x->w);
        if(res>0){
            x = x->rchild;
        }
        else if(res<0){
            x = x->lchild;
        }
        else{
            return;
        }
    }
    w->parent=y;
    if(y == NULL){
        T->lchild=w;
    }
    else if(res>0){
        y->rchild=w;
    }
    else if(res<0){
        y->lchild=w;
    }
}

//the order of dictionary

void inOrder(BTree* root){
    if(root == NULL){
        return;
    }
    else{
        inOrder(root->lchild);
        printf("%s\n",root->w);
        inOrder(root->rchild);
    }
}

int main(){
    FILE* fp;
    int c;
    char word[50];
    BTree T;
    BTree* mid;
    T.lchild=NULL;
    int count = 0;
    if( (fp = fopen("./article.txt","r"))==NULL){
        puts("error");
        exit(0);
    }
    int i=0;
    while(!feof(fp)){
        c = getc(fp);
        if((c>= 65 && c<=90) || (c>=97 && c<=122)) {//过滤非字母符号
            word[i++] = (char)tolower(c);
        }
        else if(i>0){ //碰见一个非字母符号产生单词
            word[i] = '\0';
            count++;
            i=0;
            mid =(BTree*)malloc(sizeof(BTree));
            mid->lchild=mid->rchild=mid->parent = NULL;
            strcpy(mid->w,word);
            //插入字母到平衡二叉树
            //printf("%s ***",mid->w);
            binary_insert(&T,mid);
        }
    }
    if(T.lchild == NULL){
        printf("*****");
    }
    inOrder(T.lchild);
    return 0;
}

/*
 * dosen'twork
 else if(){
    BTree mid;
    mid.lchild=mid.rchild=mid.parent=null;
    strcpy(mid.w,word);
 }

 the problem of pointer

 x is same woth w  in the function of  binaer_insert()
 * */
遇到的问题
  1. idea打开文件问题 需要在Edit Configration 里面修改当前工作路劲,不然找不到文件
  2. 局部标量使用,代码需要不断产生新的节点,如果是局部变量的话,节点会在在出了{}之后被清空,不能正常访问
阅读更多
个人分类: 北航机试
上一篇从0开始机器学习
下一篇最小生成树 Kruskai (并查集)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭