Handling collisions with Chaining
What you'll learn: How to use linked lists to prevent data loss when two different keys point to the same index in a hash table.
The "Overcrowded Mailbox" Problem
Imagine a post office with 10 mailboxes. If two different people, Smith and Smyth, are both assigned to "Box 4" based on their names, we have a collision. In a basic array, Smyth would overwrite Smith, and Smith’s mail would be lost forever.
Chaining solves this by turning every mailbox into a "hook" for a linked list. Instead of putting the mail directly into the box, we hang a list of envelopes from the hook. If a collision occurs, we simply add a new link to the chain.
How it works in code
In C, we implement chaining by making our hash table an array of pointers. Each pointer represents the "head" of a linked list. If an index is empty, the pointer is NULL. When a collision occurs, we perform a standard linked list insertion.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node {
char key[20];
int value;
struct Node* next;
};
// A table of 10 "buckets", each holding a linked list head
struct Node* hashTable[10];
void insert(char* name, int score) {
// Basic hash function: use the first letter's ASCII
int index = name[0] % 10;
// Create a new node
struct Node* newNode = malloc(sizeof(struct Node));
strcpy(newNode->key, name);
newNode->value = score;
// Insert at the front of the list (Chaining)
newNode->next = hashTable[index];
hashTable[index] = newNode;
printf("Inserted %s at index %d\n", name, index);
}
Why Chaining?
- Infinite Capacity: Theoretically, your table can hold more items than its size because the chains can grow indefinitely (as long as you have RAM).
- Simplicity: You don't have to search for a "next available" empty slot elsewhere in the array. You just go to the calculated index and add to the list.
- Graceful Degradation: If your hash function is poor and clusters data in one spot, the table doesn't break; it just becomes a bit slower as one specific chain gets longer.
Key takeaway
Chaining treats each hash table index as the head of a linked list, allowing multiple items to coexist at the same location.