我寫了這個函數來創建新節點。卡住鏈表練習
當我只添加一個節點時,程序可以正常工作,但是如果我添加第二個節點,我會遇到分段錯誤,所以問題顯然在於函數「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