我的代码(用C编写)有一个部分,给出一个链表和一个项目。该项目被附加到链接列表,我在附加之前和之后检查项目的值。
它会显示一些奇怪的行为,因为第二次附加尝试似乎会更改在附加到列表后传递的元素。
调用append函数的部分代码:
有两种情况:在第一种情况下(break == NULL),列表为空。在第二个,它不是。
if (breaks == NULL){
breaks = createNode(breakstart, breakend);
printf("Headbreaks info:\n");
printf("Next: %p\n", breaks -> next);
head = breaks;
appendToList(schedule, breaks); //append the break found to schedule list
printf("\nBreaks info after append:\n");
printf("Next: %p \n", breaks -> next);
} else {
breaks -> next = createNode(breakstart, breakend);
breaks = breaks -> next;
printf("Breaks info:\n");
printf("Next: %p \n", breaks -> next);
appendToList(schedule, breaks); //append the break found to schedule list
printf("\nBreaks info after append:\n");
printf("Next: %p \n", breaks -> next);
i++;
}
追加功能:前往列表末尾并将项目附加到其中。还有一些用于业余调试的打印功能。
void appendToList(timeblock *list, timeblock* item){
while (list -> next != NULL){
printf("(%d - %d)", list -> start, list -> end);
list = list -> next;
}
printf("\nAppend to: (%d - %d)", list -> start, list -> end);
list -> next = item;
}
节点创建:
timeblock* createNode(int start, int end){
timeblock *new = malloc(sizeof(timeblock));
new -> start = start;
new -> end = end;
new -> next = NULL;
return new;
}
输出摘录:
Headbreaks info:
Next : 00000000
Headbreaks info after append:
Next : 00000000
Breaks info:
Next : 00000000
Breaks info after append:
Next : 00322438 //I expected it to be null!
答案 0 :(得分:0)
据我所知,在第一个代码片段的第二个案例中,
部分breaks -> next = createNode(breakstart, breakend);
breaks = breaks -> next;
// some debug code
appendToList(schedule, breaks);
将一个节点插入到已经插入的列表中,让它的前任指向它。