2017-10-28 155 views
0

我使用了一個函數來將新節點插入到我的單鏈表中,但是當我插入後打印出節點內的所有值時,我只能得到第一節點:c:使用函數將新節點插入到一個單鏈表中

// Make list 
createList(head, 17); 

// Insert to list 
for (int x = 9; x > 0; x /= 3) 
{ 
    if (!insertToList(head, x)) 
    { 
     fprintf(stderr, "%s", error); 
     return 1; 
    } 
} 

功能:

bool insertToList(NODE *head, int value) 
{ 
    NODE *node = malloc(sizeof(NODE)); 
    if (node == NULL) 
     return false; 

    node -> number = value; 
    node -> next = head; 
    head = node; 
    return true; 
} 

- 輸出:17

當我不使用的功能,everythi NG按預期工作:

// Make list 
createList(head, 17); 

// Insert to list 
for (int x = 9; x > 0; x /= 3) 
{ 
    NODE *node = malloc(sizeof(NODE)); 
    if (node == NULL) 
    { 
     fprintf(stderr, "%s", error); 
     return 1; 
    } 

    node -> number = x; 
    node -> next = head; 
    head = node; 
} 

- 輸出:1 3 9 17

爲什麼?

+1

這是因爲您只修改了'head'指針的副本。 – ilotXXI

回答

1

您正在傳遞函數中的指針,更新它並且不會將其返回,在這種情況下,外部函數永遠無法知道頭部是否已更改。您也必須在for循環中適當更新頭部。

如果您不使用該函數,則for循環會在您每次插入時都知道正確的地址頭。

也許如果你返回頭指針並正確地更新它,它應該可以解決你的問題。

+0

非常感謝,您的解決方案解決了我的問題。 – taoufeqreda