gpt4 book ai didi

c - 在C中的双链表中添加 child

转载 作者:太空宇宙 更新时间:2023-11-04 03:31:33 25 4
gpt4 key购买 nike

我有一个结构定义为:

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

当一个单词的末尾包含相同字符两次或更多次时,我特别有问题。

// '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 ++;
}
}

例如,当输入单词“well”时,将打印以下输出:

  • 创建 child w
  • 创建子e
  • 创建子l
  • 遵循现有路径 l

但是这最后一个'follow existing path l'应该是'create child l'

而且我似乎想不出会歧视最后一个“l”的条件。有人可以帮我解决这个问题吗?将不胜感激。

最佳答案

问题是你没有正确地向前看。您应该检查 a->child 是否为 NULL 首先,如果是,则添加一个新节点,然后移动到该子节点。

如果 a->child 不是 NULL,那么你应该将 a->child->character 与当前字符进行比较,并且如果匹配,则移动到 a->child

我认为它应该是这样的:

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 ++;
}
}

关于c - 在C中的双链表中添加 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36070863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com