[英]Adding child in double linked list in C
我有一個結構定義為:
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”時,將打印以下輸出:
但是這最后一個“遵循現有路徑 l”應該是“創建孩子 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 ++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.