2013-03-26 123 views
2

我写了这个函数来创建新节点。卡住链表练习

当我只添加一个节点时,程序可以正常工作,但是如果我添加第二个节点,我会遇到分段错误,所以问题显然在于函数“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; 
    } 
} 

回答

3

您有运行,直到current是NULL循环......然后设置current->nexty,但current必然是NULL。

一个简单的方法来解决它是将循环改为

while (current->next != NULL){ 

我还会注意到,你应该避免全局。 current应该是一个局部变量,start应该是一个参数...我只是将它称为list,因为这就是它所代表的。 add_node应该返回list的(可能是新的)值。

2

这里:

while (current != NULL) { 
     current = current->next; 
    } 

    current->next = y; 

什么时候while停止?当current变成null。然后current->next引发分段错误。

你必须停止一个短缺NULL。将current->nextNULL进行比较,而不是current,因此在循环退出时,您仍然指向一个节点。

0

这个循环:

while (current != NULL){ 
    current = current->next; 
} 

将移动throught电流,直到current == NULL。一旦发生这样的行:

current->next = y; 

会试图推定NULL,这当然会导致seg故障。你只是想:

while(!current && current->next != NULL) 

技术上只需要while(current->next != NULL)因为你start做检查,但IMO这是很好的做法来检查指针这样的NULL你尊重它。

+0

'current = y'将会覆盖迭代变量,而不会将该项目附加到链接列表 – slezica 2013-03-26 18:54:05

+0

“在您尊重它之前检查指针为NULL是一种很好的做法。” - 它只是*被*检查。这些冗余检查实际上是非常糟糕的做法......它们使得代码难以阅读和遵循并破坏其抽象性质......在这里,有一个循环来查找空'下一个'指针,所以两个空检查循环条件不合逻辑。空列表的警卫看起来像是“if(current!= NULL){while(current-> next!= NULL){...}}'但那个守卫已经在那里了。 – 2013-03-26 23:30:36