2013-03-01 165 views
0

我試圖爲主列表中的每個元素創建一個小列表。我有主列表工作正常,但我不知道如何訪問和添加元素到小列表中。將元素添加到鏈接列表中的鏈接列表中C

struct smallList 
{ 
    char data; 
    struct smallList *next; 
}; 

struct bigList 
{ 
    char data; 
    struct bigList *next; 
    struct smallList *head; 
} *root; 

當我添加的東西向主列表,我宣佈爲每個新節點:

newNode->head = NULL; 

我用這個功能將當前指針到達主列表中的元素:

struct bigList *pointer = getPointer(root, value); 

然後,添加東西到它的smallList| using that pointer. I pass along pointer-> head`到這個函數。它不工作。

insert(pointer->head, value) 
+0

瞭解如何傳遞*指針by-address *(即指向指針的指針)。 – WhozCraig 2013-03-01 02:50:49

回答

0

正如WhozCraig所示,您可以使用指向指針的指針來解決您的問題。事情是這樣的:

void insert(struct smallList **head, char value) 
{ 
    *head = newSmallList(value, *head); 
} 

newSmallList會是這樣的:

struct smallList *newSmallList(char value, struct smallList *rest) 
{ 
    struct smallList *result = malloc(sizeof(struct smallList)); 
    result->next = rest; 
    result->data = value; 
    return result; 
} 

與當前設置的問題是,你正在過值的指針 - >頭場的(這恰好當你想要改變存儲在該字段中的內容時,該函數將被調用。下面是一個使用整數表示類似錯誤的程序:

void setFive(int i) 
{ 
    i = 5; 
} 

int main(void) 
{ 
    int myInt = 7; 
    setFive(myInt); 
    printf("%d\n", myInt); /* still 7! */ 
    return 0; 
}