简体   繁体   English

在C中的双链表中添加子项

[英]Adding child in double linked list in C

I have a struct defined as:我有一个结构定义为:

struct ac {
    int value;
    char character; 
    char * word;
    struct ac *next;
    struct ac *previous;
    struct ac *child;
    struct ac *parent;
};

I specifically have a problem when a word contains the same character twice or more at the end of the word.当一个词在词尾包含两次或更多次相同的字符时,我特别有问题。

// 'w' is the word input
int depth = 0;
ac *a; // is struct that is size of ac and contains all of the struct values set either to NULL or 0.
while(w[depth] != '\0'){
    if (a -> character == w[depth]) {
        if ((a -> value == 0) && (w[depth +1] == '\0')) {
            a -> value = 1;
            a -> word = malloc(strlen(w)+1);
            strcpy(a -> word, w);
        }
        printf("follow existing path %c\n", w[depth]);
        a = a -> child;
        depth ++;
    }
// word() is a function that reserves memory for the new word and initializes new_word problaply not relevent for this question.
    else if (a -> child == NULL) {
        new_word = word(w,depth);
        new_word -> parent = a;
        printf("create child %c\n", w[depth]);
        a -> child = new_word;
        a = new_word;
        depth ++;
    }
}

for example, when the word 'well' is the input the following output wil be printed:例如,当输入单词“well”时,将打印以下输出:

  • create child w创建子 w
  • create child e创建子 e
  • create child l创建子 l
  • follow existing path l遵循现有路径 l

But this last 'follow existing path l' should have been 'create child l'但是这最后一个“遵循现有路径 l”应该是“创建孩子 l”

and i can't seem to think of a condition that wil discriminate against that last 'l'.我似乎想不出会歧视最后一个“l”的条件。 Can someone maybe help me with this?有人可以帮我解决这个问题吗? it would be much appreciated.将不胜感激。

The problem is that you are not looking ahead properly.问题是你没有正确地向前看。 You should be checking if a->child is NULL first , adding a new node if it is and then moving to that child.你应该检查,如果a->childNULL首先,添加新节点,如果是,然后移动到那个孩子。

If a->child is not NULL , then you should compare a->child->character to the current character, and move to a->child if it matches.如果a->child不是NULL ,那么您应该将a->child->character与当前字符进行比较,如果匹配则移至a->child

I think it should look like this:我认为它应该是这样的:

int depth = 0;
ac *a;
while (w[depth] != '\0') {
    if (a->child == NULL) {
        new_word = word(w,depth);
        new_word->parent = a;
        printf("create child %c\n", w[depth]);
        a->child = new_word;
        a = new_word;
        depth ++;
    }
    else if (a->child->character == w[depth]) {
        if ((a->child->value == 0) && (w[depth +1] == '\0')) {
            a->child->value = 1;
            a->child->word = malloc(strlen(w)+1);
            strcpy(a->child->word, w);
        }
        printf("follow existing path %c\n", w[depth]);
        a = a->child;
        depth ++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM