【发布时间】:2018-07-07 17:14:23
【问题描述】:
如果我在while 条件下进行修改并将temp != NULL 更改为temp->next = NULL,则此功能不起作用。这是为什么呢?
void Print() {
printf("\n");
printf("The Library data is as follows: \n");
struct Node *temp = head; // where head is a global variable
printf("\n");
while (temp != NULL) {
printf("%25s", temp->name);
printf("%25s", temp->author);
temp = temp->next;
printf("\n");
}
}
另外,如果我修改else 块下的while 循环条件,从temp1->next = NULL 到temp1 != NULL,它不起作用。这是为什么呢?
void Insert(char q[50], char r[50]) {
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->next = NULL; // Since we are adding a node to the end, we are linking it to NULL.
strcpy(temp->name, q); // copying the contents of "q" to "temp->name"
strcpy(temp->author, r); // same
if (head == NULL) {
head = temp;
} else {
struct Node *temp1 = head;
while (temp1->next != NULL)
temp1 = temp1->next;
temp1->next = temp;
}
}
【问题讨论】:
-
因为
temp可能是NULL。您必须在取消引用它之前建立它。如果是,则您已到达链表的末尾。顺便说一句,您通常将一个项目添加到链表的 head,而不是尾部。 -
因为编写的代码表达了用于迭代/扩展链表的正确算法,而您的更改表达了不正确的算法。我建议您花一些时间使用白板:[a]->[b]->[c]->null。迭代到列表的末尾,这样你就有了 {c,null},然后用 {d,null} 扩展它并考虑它。另一个很好的练习是制定如何从列表中删除节点 b 的详细信息。
-
如果您将布尔表达式
temp- != NULL更改为赋值temp->next = NULL,则可能会发生两件事:a)temp最初是NULL,并且您有一个空指针取消引用;或 b)temp->next更改为NULL并且由于这是一个 false-y 值,因此永远不会执行循环。
标签: c linked-list nodes