fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. // Node structure definition
  6. struct Node {
  7. int data;
  8. Node* next;
  9. Node(int x) : data(x), next(nullptr) {}
  10. };
  11.  
  12. class Solution {
  13. public:
  14. // Function to search for a key in linked list
  15. bool searchKey(int n, Node* head, int key) {
  16. while(head) {
  17. if(head->data == key) return true;
  18. head = head->next;
  19. }
  20. return false;
  21. }
  22. };
  23.  
  24. // Helper function to create linked list from vector
  25. Node* createList(vector<int>& arr) {
  26. if(arr.empty()) return nullptr;
  27. Node* head = new Node(arr[0]);
  28. Node* current = head;
  29. for(int i = 1; i < arr.size(); i++) {
  30. current->next = new Node(arr[i]);
  31. current = current->next;
  32. }
  33. return head;
  34. }
  35.  
  36. // Helper function to delete linked list
  37. void deleteList(Node* head) {
  38. while(head) {
  39. Node* temp = head;
  40. head = head->next;
  41. delete temp;
  42. }
  43. }
  44.  
  45. int main() {
  46. Solution sol;
  47.  
  48. // Test Case 1: Key exists in list
  49. vector<int> arr1 = {1, 2, 3, 4, 5};
  50. Node* list1 = createList(arr1);
  51. cout << "Test 1 - Search 3 in list (1->2->3->4->5): ";
  52. cout << (sol.searchKey(5, list1, 3) ? "Found" : "Not found") << endl;
  53. deleteList(list1);
  54.  
  55. // Test Case 2: Key doesn't exist
  56. vector<int> arr2 = {10, 20, 30};
  57. Node* list2 = createList(arr2);
  58. cout << "Test 2 - Search 5 in list (10->20->30): ";
  59. cout << (sol.searchKey(3, list2, 5) ? "Found" : "Not found") << endl;
  60. deleteList(list2);
  61.  
  62. // Test Case 3: Empty list
  63. vector<int> arr3 = {};
  64. Node* list3 = createList(arr3);
  65. cout << "Test 3 - Search 1 in empty list: ";
  66. cout << (sol.searchKey(0, list3, 1) ? "Found" : "Not found") << endl;
  67. deleteList(list3);
  68.  
  69. // Test Case 4: Key is first element
  70. vector<int> arr4 = {7, 8, 9};
  71. Node* list4 = createList(arr4);
  72. cout << "Test 4 - Search 7 in list (7->8->9): ";
  73. cout << (sol.searchKey(3, list4, 7) ? "Found" : "Not found") << endl;
  74. deleteList(list4);
  75.  
  76. // Test Case 5: Key is last element
  77. vector<int> arr5 = {4, 5, 6, 7};
  78. Node* list5 = createList(arr5);
  79. cout << "Test 5 - Search 7 in list (4->5->6->7): ";
  80. cout << (sol.searchKey(4, list5, 7) ? "Found" : "Not found") << endl;
  81. deleteList(list5);
  82.  
  83. return 0;
  84. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Test 1 - Search 3 in list (1->2->3->4->5): Found
Test 2 - Search 5 in list (10->20->30): Not found
Test 3 - Search 1 in empty list: Not found
Test 4 - Search 7 in list (7->8->9): Found
Test 5 - Search 7 in list (4->5->6->7): Found