【问题标题】:Where am I making mistake in creating this function to search element from singly linked list in C++?在创建此函数以从 C++ 中的单链表中搜索元素时,我在哪里犯了错误?
【发布时间】:2019-03-16 08:03:39
【问题描述】:

我正在尝试创建一个从单链表中搜索元素并返回找到的值的地址的函数。否则返回 null。 但是当我输入值来搜索时,只搜索第一个节点/位置的值。对于所有其他输入值,它返回 NULL 并弹出消息“找不到项目” 意味着它只适用于头节点,但我不明白为什么。我认为while循环会遍历到最后,如果元素与列表中的数据匹配,它将返回根本没有发生的地址。

这是我的代码:

node *searchData(int key)
{
node *curNode=head; //head is global variable

 while (curNode!=NULL)
 {

  if(curNode->data==key)
     { 

       return curNode;
       break;

     }
else
return NULL;
curNode=curNode->link;
    }
}

我的主要功能:

 cout<<"Enter The element to search?"<<endl;
        cin>>elem;
         b=searchData(elem);//use searchData function here

         if(b==NULL)
            cout<<"Item Not Found!!";
         else
                cout<<"Element "<<elem<<" was found at address:    "<<b<<endl;



}

【问题讨论】:

    标签: c++ linked-list


    【解决方案1】:
    node *searchData(int key)
    {
      node *curNode=head; //head is global variable
    
       while (curNode!=NULL)
       {
    
         if(curNode->data==key)
         { 
           return curNode;
           // break; // redundant, you have already returned.
    
         }
         // else // no need to guard code against True, True returned.
    
         // return NULL; // your not done going thru the linked list yet
         curNode=curNode->link;
       }
       return NULL; // went thru the list to no avail.
    }
    

    短版

    node *searchData(int key)
    {
      for( node *curNode=head; curNode!=NULL; curNode=curNode->link)
        if(curNode->data==key)
          return curNode;
    
      return NULL;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-22
      • 1970-01-01
      • 2020-03-06
      • 2015-02-03
      • 2023-03-24
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多