2016-02-15 23 views
-1

在列表中傳遞列表頭作爲參數時會出現什麼問題?鏈接列表,在列表中傳遞列表頭作爲參數時不起作用

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

typedef struct node 
{ 
    int value; 
    struct node* next; 

}node; 
node* h1 = NULL; 

void ubaci(int x, node *head) 
{ 
    node *novi = (node*)malloc(sizeof(node)); 
    novi->value = x; 
    novi->next = head; 
    head = novi; 
} 

void ispisi(node *head) 
{ 
    node *temp = head; 

    while(temp != NULL) 
    { 
     printf("%d -> ",temp->value); 
     temp = temp->next; 
    } 
} 

int main() 
{ 
    int x = 0; 

    while(x<10) 
    { 
     x++; 
     ubaci(x,h1); 
    } 
    ispisi(h1); 

    return 0; 
} 

這沒有工作,我弄不明白爲什麼。但是,當我嘗試使用這些函數而不傳遞列表的頭部作爲參數和使用全局變量,而不是它的作品完美。 示例:

void ubaci(int x) 
{ 
    node *novi = (node*)malloc(sizeof(node)); 
    novi->value = x; 
    novi->next = h1; 
    h1 = novi; 
} 

void ispisi() 
{ 
    node *temp = h1; 

    while(temp != NULL) 
    { 
     printf("%d -> ",temp->value); 
     temp = temp->next; 
    } 
} 
+0

關於數以千計的鏈接列表的問題問的SO有這個確切問題的一半 - 在本地,而不是回到它改變頭。 –

+0

http://stackoverflow.com/questions/35350749/creating-linked-list-not-passing-back-to-main –

回答

0

函數參數是其局部變量。局部變量的任何改變都不會影響原始參數。

如果你想在函數中改變它們,你應該通過引用傳遞參數。

例如

void ubaci(int x, node **head) 
{ 
    node *novi = (node*)malloc(sizeof(node)); 
    novi->value = x; 
    novi->next = *head; 
    *head = novi; 
} 

函數調用可以像

相關問題