hash_table_chaining.c
hashing Implementation
76 lines1486 bytesC
1// Hash Table with Chaining
2#include <stdio.h>
3#include <stdlib.h>
4#include <string.h>
5#define TABLE_SIZE 10
6
7struct Node {
8 int key;
9 int value;
10 struct Node* next;
11};
12
13struct Node* hashTable[TABLE_SIZE];
14
15void initHashTable() {
16 for (int i = 0; i < TABLE_SIZE; i++) {
17 hashTable[i] = NULL;
18 }
19}
20
21int hashFunction(int key) {
22 return key % TABLE_SIZE;
23}
24
25void insert(int key, int value) {
26 int index = hashFunction(key);
27 struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
28 newNode->key = key;
29 newNode->value = value;
30 newNode->next = hashTable[index];
31 hashTable[index] = newNode;
32}
33
34int search(int key) {
35 int index = hashFunction(key);
36 struct Node* temp = hashTable[index];
37
38 while (temp != NULL) {
39 if (temp->key == key) {
40 return temp->value;
41 }
42 temp = temp->next;
43 }
44
45 return -1;
46}
47
48void display() {
49 for (int i = 0; i < TABLE_SIZE; i++) {
50 printf("Index %d: ", i);
51 struct Node* temp = hashTable[i];
52 while (temp != NULL) {
53 printf("(%d, %d) -> ", temp->key, temp->value);
54 temp = temp->next;
55 }
56 printf("NULL\n");
57 }
58}
59
60int main() {
61 initHashTable();
62
63 insert(1, 10);
64 insert(11, 20);
65 insert(21, 30);
66 insert(2, 40);
67 insert(12, 50);
68
69 display();
70
71 printf("\nSearch key 11: %d\n", search(11));
72 printf("Search key 25: %d\n", search(25));
73
74 return 0;
75}
76