2011-08-16 41 views
0

我嘗試用C編寫一個雙向鏈表現在我寫一個getLast元件功能:獲取最後一個元素錯誤的С雙鏈表

Dlist* getLast(Dlist **list) 
{ 
    if (list != NULL) 
    { 
     while((*list) != NULL) 
      (*list) = (*list)->next; 
    } 
    return (*list); 
} 

我得到一個segmentation fault

程序接收到的信號SIGSEGV,分段錯誤。 0x080485ce在src/dlist.c中的getLast(list = 0x804a008):29 29(* list)=(* list) - > next;

我添加了一個元素,答案沒關係。當我嘗試添加第二個元素時,出現分段錯誤。

我調用這個函數這樣:

Dlist* addItemAtStart(Dlist** list, Pair* value) 
{ 
    Dlist* last = NULL; 
    last = getLast (*list); 
    ... 
} 

有什麼不對?

回答

1

您需要的列表指針存儲在一個臨時變量,這樣你就不會破壞你的清單(或其他存儲器):

Dlist* getLast(Dlist **list) 
{ 
    if (list != NULL) 
    { 
     Dlist *ptr = *list; 
     if (ptr == NULL) 
      return NULL; 

     while(ptr->next != NULL) 
      ptr = ptr->next; 

     return ptr; 
    } 
    return NULL; 
} 
+0

謝謝你的回覆。但我得到段錯誤 - 程序接收到的信號SIGSEGV,分段錯誤。 0x0804858c在src/dlist.c中的getLast(list = 0x804a008):29 29 ptr = ptr-> next; – 0xAX

+2

'Dlist * getLast(Dlist ** list){return NULL; }' –

+0

是的,已修復。我昨晚睡了大約三個小時。 –

3

您的代碼返回NULL指針。

while(*list->next != NULL) 
0

在addItemAtStart,爲什麼您使用:的

last = getLast (*list); 

代替:

last = getLast(list); 

此外,在getLast,你不應該使用:

while((*list)->next != NULL) 

而不是:

while((*list) != NULL) 
1

您正在破壞所有列表指針。你的許多問題都源於不接受基本的列表結構。列表其第一個元素 - 您不需要將其表示爲指向該第一個元素的指針。

一些代碼來說明?

DIList * myList ; // This is your list, add elements to it 

DIList * lastElement = getLast(myList); // Last element in your list, also a list 

DIList * getLast(DIList * aList) { 
    if(aList == NULL) return NULL; 

    DIList * aNode = aList; 
    while(aNode->next != NULL) aNode = aNode->next; 

    return aNode; 
} 
相關問題