একটি সিংলি লিঙ্কড লিস্ট দেওয়া থাকলে, ঐ লিস্টে নির্দিষ্ট একটি এলিমেন্ট উপস্থিত কিনা যাচাই করতে হবে। পাওয়া গেলে "Present", না পাওয়া গেলে "Not Present" প্রিন্ট করুন।
ইনপুট-১
1→2→3→4→5→6 Searching for '7'
আউটপুট
Not Present
ইনপুট-২
1→2→3→4→5 Searching for '2'
আউটপুট
Present
সমাধানের পদ্ধতি
লিঙ্কড লিস্টে সার্চ করার দুটি পদ্ধতি রয়েছে: রিকারসিভ এবং ইটারেটিভ।
- লিস্ট খালি হলে
falseরিটার্ন করুন। - বর্তমান নোডের ডেটা টার্গেটের সমান হলে
trueরিটার্ন করুন। - রিকারসিভ পদ্ধতিতে পরবর্তী নোডে কল করুন।
- ইটারেটিভ পদ্ধতিতে লুপ চালিয়ে হেড পয়েন্টার সার্চ করুন।
উদাহরণ (রিকারসিভ)
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int d) { data = d; 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;
return searchRecursive(head->next, key);
}
int main() {
Node* head = NULL;
insertAt(head, 5); insertAt(head, 4); insertAt(head, 3);
insertAt(head, 2); insertAt(head, 1);
if (searchRecursive(head, 7))
cout << "Present" << endl;
else
cout << "Not Present" << endl;
return 0;
}
আউটপুট
Not Present