2015-04-01 72 views
0

我正在處理鏈接列表程序,並試圖刪除最後一個項目。我已經嘗試了下面的功能,但是它有問題並導致seg故障。如何刪除鏈接列表中的最後一項?

我有一個結構作爲這樣一個頭文件:

struct test{ 
char * name; 
char * type; 
struct test * next; 
}; 

而且我有一個單獨的.c文件的功能,因爲這樣的:

//NOTE Correct memory is allocated in other parts of the program 
//(i.e not in this function) 
//Also values are initialized in other functions...etc 

test * removeLastItem(test * head) 
{ 
    test * parent, * cursor; 

    if(head == NULL) //if list is empty return NULL 
    { 
     return NULL; 
    } 

    else 
    { 
     while(cursor->next != NULL) //untill last item of the list is found.. 
    { 
     parent = cursor; //parent equal to current element 
     cursor = cursor->next; //current element set to next pointer of current element 
    } 

    parent->next = NULL; //parent next pointer is now null 
} 

return head; //return the head of the list 
} 

我我不確定我的意思在這裏是否正確,但我需要返回列表的頭部,我確信我正在做這件事。任何幫助將非常感激。

+0

請在使用' - >'運算符之前將遊標初始化爲有效的東西。 「遊標」正在被使用未初始化。 – 2015-04-02 11:19:51

回答

1
  1. 您沒有初始化cursor
  2. 不要泄漏您刪除的節點。在這裏可能應該有一個free()電話。
  3. 想想你需要返回什麼,如果你的列表只有一個條目。
+0

我需要設置父項等於當前元素(即光標),要做到這一點,然後我會簡單地初始化光標在程序的開始cursor = head? – user3739406 2015-04-01 23:15:25

+0

另外,你定義了一個類型「struct test」,但是你的函數需要一個類型「test」。這些不一定是相同的類型。 「測試」在哪裏定義? – 2015-04-01 23:32:08