2014-09-23 48 views
0

以下是C中的一個簡單代碼段,用於創建鏈接列表並打印列表中包含的所有元素。最簡單的鏈接列表創建和打印數據

要求用戶輸入整數數據,直到輸入一個零標記終止用戶輸入;一旦數據保存在鏈接列表中,程序將打印存儲在列表中的所有元素,然後完成其執行。

我不能讓它跑,每次都給出了「分段故障」錯誤,請檢查並告訴我在哪裏,我錯了(使用gcc 4.8.2)

代碼:

struct node 
{ 
    int data; 
    struct node * next; 
}; 

struct node * createLinkedList() 
{ 
    int x; 
    struct node * start; 
    start = NULL; 
    printf("Input 0 to end, Insert elements :\n"); 

for(scanf("%d", &x); x ;scanf("%d", &x)) 
{ 
    struct node * temp = (struct node *) malloc(sizeof(struct node)); 
    if (temp) 
    { 
     temp->data = x; 
     temp->next = NULL; 

     if(start == NULL) { 
      start = temp; 
     } else { 
      start->next = temp; 
      start = temp; 
     } 
    } 
} 

return start; 
} 

void printLinkedList(struct node * start) 
{ 
    if (start == NULL) { 
     printf("Linked List is empty!\n"); 
    } else { 
     printf("\nPrinting Linked List : \n"); 
     struct node * s; 
     s = start; 
     while(s != NULL) 
     { 
      printf("%d\n", s->data); 
      s = s->next; 
     } 
    } 
} 

int main(int argc, char const *argv[]) 
{ 
    struct node * start; 
    start = NULL; 
    start = createLinkedList(); 
    printLinkedList(start); 
    return 0; 
} 
+0

查看for循環... omg – Igor 2014-09-23 18:16:47

+0

將它改爲* while(x!= 0)* +在適當的位置添加* scanf(「%d」,&x)*; **沒有改變O/p ** – cseav 2014-09-23 18:20:51

+1

使用你的友好的,neihbourhood調試器(或gdb),告訴我們,(和你自己),哪一行產生異常。你做這件事要容易得多,而不是我們,因爲你的代碼,環境等已經在你面前。 – 2014-09-23 18:36:34

回答

1

這部分代碼

if(start == NULL) { 
     start = temp; 
    } else { 
     start->next = temp; 
     start = temp; 
    } 

是無效的。必須有

if(start == NULL) { 
     start = temp; 
    } else { 
     temp->next = start; 
     start = temp; 
    } 

此外,你需要有一個功能,刪除列表中的所有節點。