2011-09-11 53 views
0

剛剛在C中創建鏈接列表開始。在returnLastNode的代碼中獲取運行時錯誤。我怎麼知道?當它被註釋掉時運行良好。鏈接列表中的問題

問題#1我在做什麼錯?

代碼爲我returnLastNode功能

struct Node* returnLastNode(struct LinkedList *ll) { 
    struct Node *n = ll->first; 
    struct Node *result; 
    while(1) { 
     if(n->next == NULL) { 
      result = n; 
      break; 
     } else { 
      n = n->next; 
     } 
    } 
    return result; 
} 

的使用struct的定義。

struct Node { 
    int val; 
    struct Node *next; 
}; 

struct LinkedList { 
    struct Node *first; 
}; 

LinkedList.h這裏,如果需要/感興趣。

https://github.com/MoonStruckHorrors/LinkedListC/blob/master/LinkedList.h

問題2如何新手應該調試運行時錯誤?

此外,任何其他建議表示讚賞。 :)

回答

2

在取消引用前,您從不檢查是否nNULL。這意味着您的代碼在空列表上使用時會崩潰。您也可以在if (n->next == NULL)部分中刪除變量resultreturn n;。因此,一個更好的版本代碼的可能是這樣的:

struct Node* returnLastNode(struct LinkedList *ll) { 
    struct Node *n = ll->first; 

    // checking if n is NULL here 
    while(n) { 
     if(n->next == NULL) 
      return n; 

     n = n->next; 
    } 

    return NULL; // n was NULL immediately so there is no end node 
} 

至於調試運行時錯誤時,可以使用printf檢查什麼數據是簡單的事情,而對於更復雜的東西,你可以使用調試器像gdb (或者有時IDE(如Visual Studio)帶有集成的調試器)。

+1

感謝您的提示。我正在檢查我的插入函數中的空列表(只有當鏈表非空時才使用'returnLastNode')。但即使我在那裏檢查了空的列表,我忘記初始化一個節點爲'第一',因此,在NULL上運行。 – MoonStruckHorrors

2
struct Node* returnLastNode(struct LinkedList *ll) { 
    struct Node *n = ll->first; 
    struct Node *result = n; 
    while(n != NULL) 
    { 
     result = n; 
     n = n -> next; 
    } 
    return result; 
} 

會更好。至於調試它只是練習。

0

GDB和Valgrind的是通過調試

1
typedef struct Node_t { 
    int val; 
    struct Node *next; 
}Node; 

typedef struct LinkedList_t { 
    struct Node *first; 
}LinkedList; 

調用它很酷:

 returnLastNode(SomeLinkedList.first); 

Node* returnLastNode(Node *p) { 
    while (p && p->next) p=p->next; 
    return p; 
} 

會是更好的方式...調試能力是你時間有所收穫,以唯一的出路通過坐在旁邊的一位知道要調試得更好,然後向他學習的人旁邊,一個好的方法可能更好但更慢一些,就是像瘋了一樣進行調試,並嘗試自己改進。 goodluck反正:)