使用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