2015-04-01 43 views
0

所以我的目標是刪除一個鏈表頭節點。但我有這樣的麻煩,當我有一個空的列表,這裏是我到目前爲止在C中彈出一個空鏈接列表

conscell *ll_pop(conscell *list) 
{ 
    if (list == NULL) {   // do nothing 
     return list; 
    } 
    if (list != NULL) { 
     conscell *p = list->next; 
     free(list); 
     list = p; 
     return list; 
    } 

這是實施。我們做了一系列的流行音樂。首先我們彈出兩個節點,然後彈出3個節點

conscell *ll_push(conscell *list, void *data) 
{ 
    conscell *new = xmalloc(sizeof *new); // allocate associate memory 
    new->data = data;   // assign data 
    new->next = list;   // attach the new node to the old list 
    return new; 
} 
+1

你面對什麼麻煩??? – 2015-04-01 03:40:21

+0

所以我創建了4個節點的測試文件,我彈出了5次,但它給了我消息分段錯誤@avinashpandey – Josh 2015-04-01 03:52:00

+1

你確定下一個是NULL的最後一個項目? – 2015-04-01 03:52:48

回答

2

你如何定義一個空列表?在調用該函數之前,在main中將列表設置爲NULL,並且它應該起作用。

+0

這就是我如何定義一個空列表conscell * list = NULL; \t 所以我創建了一個帶有4個節點的測試文件,並且我彈出了5次,但是它給了我消息分段錯誤@ user3711622 – Josh 2015-04-01 03:56:55

+0

如果整個列表是NULL,它就不應該有任何節點。 – MortalMan 2015-04-01 04:58:12

+0

@TimothyBrown如果列表以'NULL'開頭,那麼問題似乎不在這些功能中的任何一箇中,但可能以您如何使用它們爲準。顯示其餘的代碼。 – Havenard 2015-04-01 05:06:56

-1

你推需要分配的conscell

conscell *ll_push(conscell *list, void *data) 
{ 
    conscell *new = xmalloc(sizeof(conscell)); // allocate associate memory 
    new->data = data;   // assign data 
    new->next = list;   // attach the new node to the old list 
    return new; 
} 
0

大小,你需要做的是使用彈出的返回值來修改列表指針。

您的主要應該看起來像這樣。

int main(void) 
{ 
    conscell *list= NULL; 

    .... 

    list = ll_push(list,data1); 
    list = ll_push(list,data2); 
    list = ll_push(list,data3); 
    list = ll_push(list,data4); 

    list = ll_pop(list); 
    list = ll_pop(list);   
    list = ll_pop(list); 
    list = ll_pop(list); 
    list = ll_pop(list); 

} 

第四屆流行音樂將列表指針分配回NULL和第五,進一步啪啪只會正常返回。