使用C++在给定的单链表中搜索元素
给定一个单链表,任务是在链表中搜索特定元素。如果找到该元素,则打印“存在”,否则打印“不存在”。例如:
输入1:
1→ 2→ 3→ 4→ 5→ 6
搜索‘7’
输出:
Not Present
解释:在给定的单链表中,元素‘7’不存在,因此我们将返回输出“不存在”。
输入2:
1→ 2→ 3→ 4→ 5
搜索‘2’
输出:
Present
解释:由于在给定的单链表中存在元素‘2’,因此我们将返回输出“存在”。
解决此问题的方法
有两种方法可以在给定的单链表中搜索特定元素;我们必须递归地检查链表中是否存在一个元素。
如果链表为空,我们将返回false;否则,如果当前节点的数据值等于输入元素,我们将返回true。在另一种方法中,我们迭代地检查元素是否等于当前头指针,并相应地返回true或false。
输入并初始化一个单链表,向其中插入节点。
一个布尔递归函数searhRecursive(node*head, int element)将链表的头指针和键元素作为参数。
最初,如果head为NULL或链表为空,则返回false。
如果要搜索的元素等于链表的当前头,则返回true。
示例
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
class node{
public:
int data;
node*next;
node(int d){
data=d;
node*next= NULL;
}
};
void insertAt(node*&head, int data){
node*n= new node(data);
n->next= head;
head= n;
}
bool searchRecursive(node*head,int key){
if(head==NULL){
return false;
}
if(head->data==key){
return true;
}
else{
return searchRecursive(head->next, key);
}
}
void printNode(node*head){
while(head!=NULL){
cout<<head->data<<"->";
head=head->next;
}
cout<<endl;
}
int main(){
node*head= NULL;
insertAt(head,5);
insertAt(head,4);
insertAt(head,3);
insertAt(head,2);
insertAt(head,1);
printNode(head);
if(searchRecursive(head,7)){
cout<<"present"<<endl;
}
else{
cout<<"Not Present"<<endl;
}
}输出
运行上述代码将生成以下输出:
Not Present
由于在给定的链表1→2→3→4→5中,元素‘7’不存在,因此我们返回“不存在”。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP