2011-04-30 61 views
0

這是我的代碼,用於在鏈接列表中搜索,但它不會給我正確的結果。請幫助我,我很擔心它。在鏈接列表中搜索

search() { 

    char ser[20]; 
    cout << "enter data to be searched" << endl; 
    gets(ser); 

    for (start=head; start->ptr!=NULL; start=start->ptr) { 
    if (start->info == ser) { 
     cout << "ok" << endl; 
     break; 
    } 
    } 
    cout << "not found" << endl; 
} 

感謝, 賽馬坎瓦爾Bhutta

回答

1

你怎麼想到這個做什麼?

if (start->info == ser) { 

它檢查是否start->info指向ser數組的開始。您可能想要使用strcmp來比較字符串。

0

要比較2個字符串,請使用strcmp()。使用「==」將比較2個指針,而不是字符串的內容。

0

就你而言,你應該比較字符串的內容而不是它們的起始地址。

正確版本

void search() { 

    char ser[20]; 
    cout << "enter data to be searched" << endl; 
    gets(ser); 

    for (start=head; start->ptr!=NULL; start=start->ptr) 
    { 
    if (strcmp(start->info, ser) == 0) 
    { 
     cout << "found" << endl; 
     return; 
    } 
    } 
    cout << "not found" << endl; 
} 

多一點提

您需要檢查headfor循環之前第一。否則,如果head爲NULL,程序將崩潰。

+0

很難說gets()是正確的。 – 2011-04-30 08:37:59

0

您的環路狀況非常危險。您不檢查'開始'本身是否爲空或不是。此外,您正在比較Next元素是否可用,從而在下一個元素不可用時丟失當前元素。字符串比較也是不正確的。更新你的循環如下:

for (start=head; start != NULL; start=start->ptr) { 
     if (strcmp(start->info, ser) == 0) { 
      cout << "ok" << endl; 
      break; 
     } 
     } 
1

賽馬,

首先,歡迎到論壇,也歡迎計算機編程的美妙,令人沮喪的,和富有成效的世界。

其次,我編輯了你的帖子。如果你現在點擊edit按鈕,你會看到如何佈局你的源代碼,所以論壇很好地顯示它。

第三,我想你的意思是return你說的break ......這樣你就不會看到「找不到」消息。那是你想要的嗎?第四,我建議你從列表搜索部分分離用戶輸入部分......它很容易完成,並且它使得鏈接列表搜索對任何字符串(來自任何地方)都可用,而不僅僅是一個用戶現在進入。同樣,將搜索輸出分離出來,這樣您可以稍後重新使用搜索,以產生適合這種情況的任何輸出。

最後,這些變量名稱(原諒我)吸!

所以......我的ANSI-C版本將是這個樣子:

int contains(char* target) { 
    for (Node node=head; node->next!=NULL; node=node->next) { 
    if (strcmp(node->data, target)==0) { 
     return 0; // TRUE 
    } 
    } 
    return 1; // FALSE 
} 

以上是一個鏈表的部分,這有助於使你的代碼「相當標準」的名字,許多更具可讀性,因此可維護。此外WTF是一個「服務」......怎麼樣「目標」?

如果這一切都在你的頭上,那麼不要擔心它......現在就忽略這個建議。

乾杯。基思。

+1

爲什麼你用0表示真,1表示假? – 2011-04-30 08:50:31

0

獲取是危險的,因爲它不提供指定緩衝區長度的方法。有一些替代方案可以用於char數組,但在這裏使用std :: string會更簡單。我已經將查找功能解壓到一個單獨的函數中。這使您可以使用相同的功能來搜索列表,而不管您如何獲得搜索值或您想要如何處理它。

Node* find(Node* head, const string& needle) { 
    for (; head; head = head->ptr) { 
     if (head->info == needle) { 
      return head; 
     } 
    } 
    return 0; 
} 

void search(Node* head) { 
    string needle; 
    cout << "Data to be searched: "; 
    if (!getline(cin, needle)) { 
     // Do something appropriate, such as throw an exception, return 
     // an error code (if you change the function's interface), or 
     // simply exit. 
     abort(); 
    } 

    Node* found = find(head, needle); 
    if (found) { 
     cout << "Found.\n"; 
    } 
    else { 
     cout << "Not found.\n"; 
    } 
}