2015-02-10 20 views
0

這裏是我用C編寫鏈接列表的代碼。它在while循環執行一次後給出運行時錯誤。 Plz幫助我糾正我的代碼。 (完全搞不清楚錯誤在哪裏)。我首先創建一個頭節點,然後向它添加子節點。通過頭部和節點製作鏈接列表

#include <stdio.h> 
#include <stdlib.h> 

typedef struct node nd; 
typedef nd *link; 

struct node{ 
    int data; 
    link next; 
}; 

typedef struct { 
    int size; 
    link head; 
}list; 

void create(link temp) 
{ 
    link new; 
    new=(link)malloc(sizeof(nd)); 
    printf("enter data: "); 
    scanf("%d",new->data); 
    temp->next=new; 
    temp=temp->next; 
} 

list createlist() 
{ 
    list sl; 
    sl.size=0; 
    sl.head=0; 
    return sl; 
} 

int main() 
{ 
    list sl; 
    sl=createlist(); 
    link temp; 
    temp=sl.head; 
    char c; 
    while (1) 
    { 
     printf("Add node?: "); 
     scanf(" %c",&c); 
     if (c=='y') 
      { 
      create(temp); 
      sl.size++; 
      } 
     else 
      break; 
    } 
    return 0; 
} 
+0

它在哪一行崩潰?你給了什麼輸入? – 2015-02-10 03:19:57

+1

將create()中的變量'new'更改爲其他值將會很好。這不是你的問題,只是不好的風格。 – KeithSmith 2015-02-10 03:20:28

+0

不應該scanf(「%d」,new-> data);是scanf(「%d」,&new-> data); – KeithSmith 2015-02-10 03:28:31

回答

2

createlist()函數返回到本地變量超出範圍則返回在經過了參考。您應該返回一個基於堆的值:

list* createlist() { 
    list* sl = (list*)malloc(sizeof(list)); 
    sl->size=0; 
    sl->head=0; 
    return sl; 
    } 
0

最初temp指向NULL。 temp = sl.head;

在create(temp)temp-> next = new;

您正在取消引用NULL,地址0x0。當我這樣做時,我會遇到分段錯誤。

需要更改算法。 調試器立即顯示此問題。

0

您可以使用指向temp的指針。如果你沒有使用指向節點的typedef,讀起來會更容易。我沒有測試過這個,但它應該是關閉的:

nd ** create(nd **temp) 
{ 
    nd *new; 
    new=(nd *)malloc(sizeof(nd)); /* this cast shouldn't be needed */ 
    printf("enter data: "); 
    scanf("%d",&(new->data)); 
    new->next = NULL; 
    *temp = new; 
    return &(new->next); 
} 
/* ... */ 

int main() 
{ 
nd **temp; 
temp = &(sl.head); 
/* ... */ 
     temp = create(temp); 
/* ... */ 
}