使用C ++在给定的单链表中搜索元素

给定一个单链表,任务是在链表中搜索特定元素。如果找到该元素,则打印“存在”,否则打印“不存在”。例如,

输入1 -

1→ 2→ 3→ 4→ 5→ 6

搜索“ 7”

输出-

Not Present

说明-在给定的单链列表中,元素“ 7”不存在,因此我们将输出返回为“不存在”。

输入- 2 -

1→ 2→ 3→ 4→ 5

搜索“ 2”

输出-

Present

解释-由于在给定的单链列表中元素'2'存在,因此我们将输出返回为“ Present”。

解决这个问题的方法

有两种方法可以在给定的单链列表中搜索特定元素:我们必须递归检查链接列表中是否存在一个元素。

如果链表为空,则返回false;否则,如果当前节点的数据值等于输入元素,则返回true。在另一种方法中,我们迭代检查元素是否等于当前的头部指针,并相应地返回true或false。

  • 输入并通过在其中插入节点来初始化单链列表。

  • 布尔型递归函数searhRecursive(node * head,int元素)将链表的头指针和键元素作为参数。

  • 最初,如果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”不存在,因此我们返回“不存在”。

以上是 使用C ++在给定的单链表中搜索元素 的全部内容, 来源链接: utcz.com/z/333834.html

回到顶部