【发布时间】: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