2014-12-04 82 views
1

所以這是一個我在類的問題。規定是我們使用下面的代碼作爲我們的主要而不編輯它從已創建的節點創建鏈接列表。進入段錯誤

int main(void) { 

    // a reference to the head of our list 
    node *head = NULL; 
    node ** list = &head; 

    // the nodes we will put in our list 
    node a = {6,NULL}; 
    node b = {8,NULL}; 
    node c = {4,NULL}; 
    node d = {10,NULL}; 
    node e = {2,NULL}; 

    // build the list 
    append(list, &a); 
    append(list, &b); 
    prepend(list, &c); 
    append(list, &d); 
    prepend(list, &e); 

    // print the list 
    print(list); 

    // test the find function 
    int value; 
    for (value = 1; value <= 10; value++) { 
    node * found = find(list, value); 
    if (found == NULL) 
     printf("Node %d not found...\n", value); 
    else 
     printf("Found node %d!\n", found->content); 
    } 

    // test delete function 
    delete(list, 4); 
    delete(list, 8); 
    print(list); 

    return 0; 
} 

我們需要在我們自己的主體中創建所有的函數。目前只是在附加功能上工作。有人告訴我,追加功能應該是這樣的:append(node * list, node * new_node);

tydef stuct node_t { 
    int content; 
    struct node_t *next; 
} node; 

這是我爲節點聲明。

void append(node ** list, node * new_nodes) { 
    node ** current = list; 
    while ((*current)->next != NULL) { 
    (*current) = (*current)->next; 
    } 
    (*current)->next = new_node; 
    list = current; 
} 

這是我的追加函數。我相對確定最後一行是錯誤的,但我仍然無法開始。任何想法或建議都會很棒。

+0

做的就是繪製節點圖,並仔細改變的圖,而指針的最好的事情通過代碼閱讀。 – 2014-12-04 08:37:11

回答

0

由於名單是按值傳遞,你可以使用它作爲一個臨時變量:

void append(node **list, node *new_node) 
{ 
    while(*list != NULL) 
     list = &((*list)->next); 
    *list = newNode; 
} 
+0

謝謝。通過一點工作,這讓我開始了。我沒有足夠的聲望來投票給你。我道歉。 – 2014-12-04 15:45:20

3

考慮以下兩行:

node *head = NULL; 
node ** list = &head; 

這使得list點的指針NULL

然後考慮:

append(list, &a); 

和(從append功能):

node ** current = list; 
while ((*current)->next != NULL) { 

你傳遞一個指針的指針NULLappend功能,這意味着*current是指向NULL,然後你解引用NULL指針導致undefined behavior和你的崩潰。

+0

Roger。所以我需要將指針指向&a,因爲它是我擁有的唯一位置,並將其設置爲頭部。還要確保我們在未來追加列表的末尾? – 2014-12-04 08:47:25

0

頭和列表尚未設置 - 如果列表== NULL,則必須首先檢查。

void append(node ** list, node * new_nodes) { 
    node **current = list; 
    if (*current == NULL) { 
     *current = node; 
     return; 
    } 
    while ((*current)->next != NULL) { 
     (*current) = (*current)->next; 
    } 
    (*current)->next = new_node; 
}