2015-03-02 79 views
-1

我想寫一個方法來找出一個給定的值是否存在於一個鏈表中。C找出一個值是否存在於一個鏈表中

// Returns true if the value exists in the list. 
int llist_exists(LinkedList * list, int value) { 

     LinkedList *e; 
     e = list->head; 
     int result = 0; 

     while(e != NULL) 
     { 
       if(e == value) 
       { 
         result = 1; 
         break; 
       } 
     } 

     return result; 

}

+2

你的問題是什麼?什麼不按預期工作? – EWit 2015-03-02 20:16:49

回答

2

在你的代碼中,你正在比較一個int指針和@xxbbcc指出的指針,永遠不要在列表中向前移動。 如果我們假設你的LinkedList類如下:

class LinkedList 
{ 
public: 
    int value; 
    LinkedList *next; 
}; 

int llist_exists(LinkedList * list, int value) { 

     LinkedList *e; 
     e = list->head; 
     int result = 0; 

     while(e != NULL) 
     { 
       if(e->value == value) 
       { 
         result = 1; 
         break; 
       } 
       e = e->next; 
     } 
     return result; 
} 
+0

OP表示C,而不是C++。另外,你的LinkedList結構沒有'head'字段。但總體思路很好。 – 2015-03-11 22:42:19

1

你可能有一個無限循環,因爲你永遠不設置e到列表中的下一個條目。您需要進入while循環中的下一個條目;是這樣的:

while(e != NULL) 
{ 
    if(e.value == value) 
    { 
     result = 1; 
     break; 
    } 

    e = e->next; 
} 

此外,作爲@sithereal指出的那樣,你比較e的價值,但e是條目指針,而不是價值。

相關問題