#include <iostream> int arr[] = {1, 3, 5, 7, 9}; struct Node { int val; Node* next; }; Node* head = new Node{1, new Node{3, new Node{5, new Node{7, new Node{9, nullptr}}}}}; int searchArray(int* arr, int size, int target) { for (int i = 0; i < size; i++) { if (arr[i] == target) return i; } return -1; } int searchLinkedList(Node* head, int target) { int index = 0; while (head != nullptr) { if (head->val == target) return index; head = head->next; index++; } return -1; } int main() { int idxArr = searchArray(arr, 5, 5); int idxList = searchLinkedList(head, 5); std::cout << idxArr << " " << idxList << std::endl; return 0; }
The value 5 is at index 2 in the array (0-based). The linked list nodes are also counted from 0, so 5 is at index 2 there as well.
Hash maps provide average O(1) lookup time by key, arrays provide O(n) unless the index is known, and linked lists provide O(n) lookup time.
#include <iostream> struct Node { int key; Node* next; }; Node* hashTable[10] = {nullptr}; void insert(int key) { int index = key % 10; Node* newNode = new Node{key, hashTable[index]}; hashTable[index] = newNode; } bool search(int key) { int index = key % 10; Node* curr = hashTable[index]; while (curr != nullptr) { if (curr->key == key) return true; curr = curr->next; } return false; } int main() { insert(1); insert(11); insert(21); std::cout << (search(11) ? "Found" : "Not Found") << std::endl; return 0; }
Keys 1, 11, and 21 all hash to index 1 (key % 10). They are inserted at the head of the linked list at that bucket. Searching for 11 finds it in the chain, so 'Found' is printed.
Arrays store elements in contiguous memory, so accessing by index is direct and fast. Linked lists require visiting each node one by one until the target is found, which is slower.
#include <iostream> #include <unordered_map> #include <string> struct Node { int val; Node* next; }; int main() { int arr[] = {2, 4, 6, 8}; Node* head = new Node{1, new Node{3, new Node{5, nullptr}}}; std::unordered_map<int, std::string> map = {{7, "seven"}, {8, "eight"}}; // Search array bool foundArr = false; for (int i = 0; i < 4; i++) { if (arr[i] == 7) { foundArr = true; break; } } // Search linked list bool foundList = false; Node* curr = head; while (curr != nullptr) { if (curr->val == 7) { foundList = true; break; } curr = curr->next; } // Search hash map bool foundMap = map.find(7) != map.end(); std::cout << foundArr << " " << foundList << " " << foundMap << std::endl; return 0; }
The array does not contain 7, so foundArr is 0. The linked list nodes are 1,3,5, so foundList is 0. The hash map contains key 7, so foundMap is 1.
