C++ 在链表中搜索

C++ 在链表中搜索,c++,C++,这是我在链表中搜索的代码,但它没有给出正确的结果。请帮帮我,我很担心 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 <

这是我在链表中搜索的代码,但它没有给出正确的结果。请帮帮我,我很担心

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;
}
search(){
char-ser[20];
法院(ptr){
如果(开始->信息==ser){

难道你认为这能做什么

if ( start->info == ser ) {

它正在检查
start->info
是否指向
ser
数组的开头。您可能希望使用
strcmp
来比较字符串。

要比较两个字符串,请使用strcmp()。使用“==”将比较两个指针,而不是字符串的内容。

在您的情况下,您应该比较字符串的内容,而不是字符串的起始地址

正确版本

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;
}
void搜索(){
char-ser[20];
法院(ptr)
{
如果(strcmp(开始->信息,服务)==0)
{

cout您的循环条件是危险的。您没有检查“开始”本身是否为空。此外,您正在比较下一个元素是否可用,从而在下一个元素不可用时丢失当前元素。字符串比较也不正确。请按以下方式更新您的循环:

for ( start=head; start != NULL; start=start->ptr ) {
        if ( strcmp(start->info, ser) == 0 ) {
          cout << "ok" << endl;
          break;
        }
      }
for(start=head;start!=NULL;start=start->ptr){
如果(strcmp(开始->信息,服务)==0){
不能Saima

首先,欢迎来到论坛,也欢迎来到精彩、令人沮丧和富有成果的计算机编程世界

其次,我编辑了你的文章。如果你现在点击
编辑
按钮,你将看到如何布局你的源代码,因此论坛会很好地显示它

第三,我猜你的意思是
return
你说的
break
…这样你就不会一直看到“notfound”消息。这就是你想要的吗

第四,我建议您将用户输入部分与列表搜索部分分开……这很容易完成,而且它使链接列表搜索可以用于任何字符串(从任何地方),而不仅仅是用户现在输入的内容。同样,将输出与搜索分开,这样以后您就可以重复使用搜索,以生成任何适合情况的输出

最后,那些变量名(请原谅)太糟糕了

所以…我的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是一个“ser”…那么“target”呢

如果这是你的全部想法,那么不要担心它…只是暂时忽略这个建议


Cheers.Keith.

Gets是危险的,因为它无法指定缓冲区的长度。有其他方法可用于字符数组,但在这里使用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";
    }
}
节点*查找(节点*头、常量字符串和指针){
用于(;头部;头部=头部->ptr){
如果(头部->信息==打捆针){
回流头;
}
}
返回0;
}
无效搜索(节点*头){
线针;

你为什么用0表示真,用1表示假?