2011-04-30 80 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"; 
    } 
}