#include <iostream>
#include <vector>
using namespace std;
// Node structure definition
struct Node {
int data;
Node* next;
Node(int x) : data(x), next(nullptr) {}
};
class Solution {
public:
// Function to search for a key in linked list
bool searchKey(int n, Node* head, int key) {
while(head) {
if(head->data == key) return true;
head = head->next;
}
return false;
}
};
// Helper function to create linked list from vector
Node* createList(vector<int>& arr) {
if(arr.empty()) return nullptr;
Node* head = new Node(arr[0]);
Node* current = head;
for(int i = 1; i < arr.size(); i++) {
current->next = new Node(arr[i]);
current = current->next;
}
return head;
}
// Helper function to delete linked list
void deleteList(Node* head) {
while(head) {
Node* temp = head;
head = head->next;
delete temp;
}
}
int main() {
Solution sol;
// Test Case 1: Key exists in list
vector<int> arr1 = {1, 2, 3, 4, 5};
Node* list1 = createList(arr1);
cout << "Test 1 - Search 3 in list (1->2->3->4->5): ";
cout << (sol.searchKey(5, list1, 3) ? "Found" : "Not found") << endl;
deleteList(list1);
// Test Case 2: Key doesn't exist
vector<int> arr2 = {10, 20, 30};
Node* list2 = createList(arr2);
cout << "Test 2 - Search 5 in list (10->20->30): ";
cout << (sol.searchKey(3, list2, 5) ? "Found" : "Not found") << endl;
deleteList(list2);
// Test Case 3: Empty list
vector<int> arr3 = {};
Node* list3 = createList(arr3);
cout << "Test 3 - Search 1 in empty list: ";
cout << (sol.searchKey(0, list3, 1) ? "Found" : "Not found") << endl;
deleteList(list3);
// Test Case 4: Key is first element
vector<int> arr4 = {7, 8, 9};
Node* list4 = createList(arr4);
cout << "Test 4 - Search 7 in list (7->8->9): ";
cout << (sol.searchKey(3, list4, 7) ? "Found" : "Not found") << endl;
deleteList(list4);
// Test Case 5: Key is last element
vector<int> arr5 = {4, 5, 6, 7};
Node* list5 = createList(arr5);
cout << "Test 5 - Search 7 in list (4->5->6->7): ";
cout << (sol.searchKey(4, list5, 7) ? "Found" : "Not found") << endl;
deleteList(list5);
return 0;
}