DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS
Implement Hashing with Separate Chaining
Learn how to implement hashing with separate chaining using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0: 15 10 2: 17 12 7
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdlib.h>
struct Node { int key; struct Node *next; };
void insert(struct Node *table[], int key)
{
int bucket = key % 5;
struct Node *node = malloc(sizeof *node);
if (node == NULL) exit(EXIT_FAILURE);
node->key = key; node->next = table[bucket]; table[bucket] = node;
}
void clear(struct Node *table[])
{
for (int bucket = 0; bucket < 5; bucket++)
while (table[bucket] != NULL) {
struct Node *removed = table[bucket];
table[bucket] = removed->next; free(removed);
}
}
int main(void)
{
struct Node *table[5] = {NULL};
int keys[] = {10, 15, 7, 12, 17};
for (int index = 0; index < 5; index++) insert(table, keys[index]);
for (int bucket = 0; bucket < 5; bucket++) {
printf("%d:", bucket);
for (struct Node *node = table[bucket]; node != NULL; node = node->next) printf(" %d", node->key);
putchar('\n');
}
clear(table);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0: 15 10 2: 17 12 7
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Store colliding keys in a linked list owned by the hashed bucket.
- Display the computed result.
Store colliding keys in a linked list owned by the hashed bucket.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
