#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Linked List Node
typedef struct Node {
int val;
struct Node* next;
} Node;
// Create new node
Node* newNode(int val) {
Node* node = (Node*)malloc(sizeof(Node));
node->val = val;
node->next = NULL;
return node;
}
// Insert at end of linked list
void insertLinkedList(Node** head, int val) {
Node* node = newNode(val);
if (*head == NULL) {
*head = node;
return;
}
Node* curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = node;
}
// Search in linked list
int searchLinkedList(Node* head, int target) {
Node* curr = head;
while (curr != NULL) {
if (curr->val == target) {
return 1; // found
}
curr = curr->next; // advance curr to next node
}
return 0; // not found
}
// Search in array
int searchArray(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return 1; // found
}
}
return 0; // not found
}
// Simple hash map with chaining
#define BUCKETS 5
typedef struct HNode {
int key;
struct HNode* next;
} HNode;
HNode* hashTable[BUCKETS];
int hashFunction(int key) {
return key % BUCKETS;
}
void insertHashMap(int key) {
int index = hashFunction(key);
HNode* node = (HNode*)malloc(sizeof(HNode));
node->key = key;
node->next = hashTable[index];
hashTable[index] = node;
}
int searchHashMap(int key) {
int index = hashFunction(key);
HNode* curr = hashTable[index];
while (curr != NULL) {
if (curr->key == key) {
return 1; // found
}
curr = curr->next; // advance curr to next node in bucket
}
return 0; // not found
}
int main() {
int arr[] = {10, 20, 30, 40};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 30;
// Linked List setup
Node* head = NULL;
for (int i = 0; i < size; i++) {
insertLinkedList(&head, arr[i]);
}
// Hash Map setup
for (int i = 0; i < size; i++) {
insertHashMap(arr[i]);
}
// Search in Array
printf("Array search for %d: %s\n", target, searchArray(arr, size, target) ? "Found" : "Not Found");
// Search in Linked List
printf("Linked List search for %d: %s\n", target, searchLinkedList(head, target) ? "Found" : "Not Found");
// Search in Hash Map
printf("Hash Map search for %d: %s\n", target, searchHashMap(target) ? "Found" : "Not Found");
return 0;
}
curr = curr->next; // advance curr to next node
advance curr to next node — keeps traversing until value found or end
for (int i = 0; i < size; i++) { if (arr[i] == target) return 1; }
scan array elements one by one to find target
curr = hashTable[index]; while (curr != NULL) { if (curr->key == key) return 1; curr = curr->next; }
traverse linked nodes in hash bucket to find key
Array search for 30: Found
Linked List search for 30: Found
Hash Map search for 30: Found