2013-02-27 163 views
0

我試圖使用節點添加到鏈接列表的前面如下:使用函數指針作爲參數

struct Node *addFront(struct List *list, void *data) { 

到目前爲止,我有以下幾點:

struct Node *front = (struct Node *) malloc(sizeof(struct Node)){ 
    if(front == NULL) { 
     return NULL; 
    } 

    front->data = data; 

    if(list->head == 0) { 
     list->head = front; 
     front->next = NULL; 
    } 
    else { 
     list->head = front; 
     *front->next =* 
    } 

    return front; 
} 

我如果它不是第一個創建的節點,那麼添加的節點會指向什麼......我想說的是: front-> next = list; 但是List是List的類型,所以我確定我會得到一些不兼容的賦值錯誤。要做到這一點,最好的方法是什麼?

回答

0
Node *oldHead = list->head; 
list->head = front; 
front->next =oldHead; 

存儲舊的磁頭,並將其分配給front->next

或者只是

front->next =list->head; 
list->head = front; 

就足夠了。

+0

謝謝!我是一個新手(如你所見)。非常感謝。 – user1889966 2013-02-27 02:58:53