我写了这个函数来创建新节点。卡住链表练习
当我只添加一个节点时,程序可以正常工作,但是如果我添加第二个节点,我会遇到分段错误,所以问题显然在于函数“add_node()”的“else”部分,但我可以'弄明白了。
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
char *city;
struct node *next;
}node;
node *start = NULL;
node *current;
void add_node(char *cityname) {
node *y = malloc(sizeof(node));
y->city = cityname;
y->next = NULL;
current = start;
if(start == NULL) {
start = y;
} else {
while (current != NULL) {
current = current->next;
}
current->next = y;
}
}
int main() {
add_node("Paris");
add_node("London");
current = start;
while(current != NULL) {
printf("%s\n", current->city);
current = current->next;
}
}
'current = y'将会覆盖迭代变量,而不会将该项目附加到链接列表 – slezica 2013-03-26 18:54:05
“在您尊重它之前检查指针为NULL是一种很好的做法。” - 它只是*被*检查。这些冗余检查实际上是非常糟糕的做法......它们使得代码难以阅读和遵循并破坏其抽象性质......在这里,有一个循环来查找空'下一个'指针,所以两个空检查循环条件不合逻辑。空列表的警卫看起来像是“if(current!= NULL){while(current-> next!= NULL){...}}'但那个守卫已经在那里了。 – 2013-03-26 23:30:36