从文件中读取单词并存储在树中

时间:2015-05-22 13:19:03

标签: c debugging tree fgets

我正在尝试从文件中读取文字并将其存储在树中。

    Dictionary newDictionary(FILE *inf)
{
    assert(inf != NULL);
    int i;
    char word[MAX_WORD_SIZE];
    Dictionary dict = malloc(sizeof(DictionaryRep));
    dict->tree = newTree(); 

    while (fgets(word,MAX_WORD_SIZE,inf) != NULL) {
        int n = strlen(word);
        word[n-1] = '\0'; 
        if (strcmp(word,"") != 0 && strlen(word) > 2 && strlen(word) < 7) {
            for(i = 0; word[i] != '\0'; i++){
                if(word[i] >= 'A' && word[i] <= 'Z'){
                    word[i] += ' ';
                }                    
            }  
        TreeInsert(dict->tree,word);
        }
    }     printf("%d\n",TreeNumNodes(dict->tree));         
    return dict;
}

这段代码最终做的是:从文件中读取一个单词,存储它,然后读取下一个单词,存储它等等。但是,它似乎没有构建一棵树。它从TreeNumNodes打印1,当我要求它显示树时,它总是打印一个单词,然后是下一个单词,依此类推,因为fgets在文件中前进。

TreeInsert的实现:

Tree thisTree;
typedef char *Key;
typedef Key Item; 

void TreeInsert(Tree t, Item it)
{
    thisTree = t;
    t->root = insertRB(t->root, it,0);
        t->root->colour = BLACK;
}


Link insertRB(Link t, Item it, int inRight){
    if (t == NULL) return newNode(it,RED);
    // node is a 4-node; lift it
    if (isRed(t->L) && isRed(t->R)) {
        t->colour = RED;
        t->L->colour = BLACK;
        t->R->colour = BLACK;
    }
    int diff = cmp(key(it),key(t->value));
    if (diff == 0)
        t->value = it;
    else if (diff < 0) {
        t->L = insertRB(t->L, it, 0);
        if (isRed(t) && isRed(t->L) && inRight){

            t = rotateR(t);

        }
        if (isRed(t->L) && isRed(t->L->L)) {

            t = rotateR(t);
            t->colour = BLACK;
            t->R->colour = RED;
        }
    } else if (diff > 0) {
        t->R = insertRB(t->R, it, 1);
        if (isRed(t) && isRed(t->R) && !inRight){

            t = rotateL(t);
        }
        if (isRed(t->R) && isRed(t->R->R)) {

            t = rotateL(t);
            t->colour = BLACK;
            t->L->colour = RED;
        }
    }
    return t;
}

0 个答案:

没有答案