algoritmauzmanı
Sign in
TREN
9.3Separate Chaining (Linked List)
Lesson 9.3.1

Insert with chaining

Collisions cannot be avoided: two different keys can land in the same bucket. solves this in the most direct way: every holds the head of a instead of a single key. All the keys that land in the same bucket stay side by side in that list. In this lesson you build the table and write its first operation, insertion.

What you will learn
  • How a chained table is built from an array of pointers and linked lists
  • Why the chain is walked before inserting and why the new node goes at the head
  • Why the cost of insertion depends on the chain length, that is on the load factor
6 minTime O(1 + α)Memory O(1)C · Java · Python

1Idea

The table is an array of M = 11 pointers: buckets[i] points to the first node of bucket i's chain. At the start every bucket is NULL, so every chain is empty. A key's bucket is found with hash(key) = key % M.

Insertion has two steps. First the bucket's chain is walked from start to end to see whether the key is already there; the table never keeps the same key twice, so if it is there the function returns false. If not, a new node is made and linked at the head of the chain: node->next = buckets[i], then buckets[i] = node. This is exactly inserting at the head of a linked list.

Inserting at the head takes constant time; inserting at the end would need a walk to find the end. The order inside a chain does not matter, so the head is the cheapest place. The duplicate check still walks the chain, so the cost of insertion depends on the length of the chain.

With open addressing the table can fill up; with chaining it cannot. A bucket can hold as many nodes as you like, and the number of keys can be larger than the number of buckets. That is why the C code returns false only when the key already exists or malloc fails.

2Step by step

The table in the drawing holds 22, 37, 15 and 31; 37 and 15 landed in the same bucket (4), so they share a chain. Now 26 is inserted. At each step the matching line of code lights up.

buckets (M = 11)NULLNULLNULL01234567891022?37?15?31?26?tempnode
  1. Start. Only three of the 11 buckets are in use. Bucket 4's chain has two nodes: 37 and 15. Empty buckets hold NULL.
  2. The bucket is computed: 26 % 11 = 4. 26 also lands in bucket 4; this is a .
  3. Check whether the key is already there. temp starts at the first node of the chain.
  4. 37 is not 26. Keep going.
  5. temp moves to the next node, 15.
  6. 15 is not 26 either.
  7. temp is NULL: the end of the chain was reached and 26 was not found. The insertion can go ahead.
  8. A new node is made and 26 is written into it. It is not linked anywhere yet.
  9. The new node's next field points to the bucket's current first node (37).
  10. The bucket now points to the new node. The chain is 26, 37, 15. Because next was linked first, no node was lost.
  11. The counter goes up by one and the function returns true. The table holds 5 keys.

#define M 11 struct Node {    int data;    struct Node* next;}; struct HashTable {    struct Node* buckets[M];    int count;}; int hash(int key) {    return key % M;} void create(struct HashTable* t) {    for (int i = 0; i < M; i++)        t->buckets[i] = NULL;       // every chain is empty    t->count = 0;} bool insert(struct HashTable* t, int key) {    int i = hash(key);    struct Node* temp = t->buckets[i];    while (temp != NULL) {          // is the key already there?        if (temp->data == key)            return false;        temp = temp->next;    }    struct Node* node = malloc(sizeof(struct Node));    if (node == NULL) return false;    node->data = key;    node->next = t->buckets[i];     // at the head of the chain    t->buckets[i] = node;    t->count++;    return true;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} class ChainedHashTable {    static final int M = 11;    Node[] buckets = new Node[M];   // every chain is empty    int count = 0;     int hash(int key) {        return key % M;    }     boolean insert(int key) {        int i = hash(key);        Node temp = buckets[i];        while (temp != null) {          // is the key already there?            if (temp.data == key)                return false;            temp = temp.next;        }        Node node = new Node(key);        node.next = buckets[i];         // at the head of the chain        buckets[i] = node;        count++;        return true;    }}
M = 11 class Node:    def __init__(self, data):        self.data = data        self.next = None class ChainedHashTable:    def __init__(self):        self.buckets = [None] * M   # every chain is empty        self.count = 0     def h(self, key):        return key % M     def insert(self, key):        i = self.h(key)        temp = self.buckets[i]        while temp is not None:         # is the key already there?            if temp.data == key:                return False            temp = temp.next        node = Node(key)        node.next = self.buckets[i]     # at the head of the chain        self.buckets[i] = node        self.count += 1        return True

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(1 + α)

The bucket is found in O(1), then the chain is walked. The average chain length is the α = n / M, so insertion takes O(1 + α) on average. If every key lands in the same bucket it becomes O(n).

Memory
O(1)

One node is made for each inserted key; the extra room per operation is constant.

Without the duplicate check insertion would always be O(1). That is why some books say "insertion with chaining is O(1)"; here the check is done to avoid duplicates. If α is kept small the difference does not matter; that is what growing the table is for.

4Common mistake

A common mistake is pointing the bucket at the new node first and setting next afterwards:

t->buckets[i] = node;          // the bucket changed firstnode->next = t->buckets[i];    // node now points to itself

When the second line runs, buckets[i] is already the new node; node->next points to itself and the whole old chain is lost. The first operation that walks the chain also loops forever. The order is always the same: first the new node points to the old head, then the bucket points to the new node.

5Try it

5, 16 and 27 are inserted in that order into an empty table with M = 11. How does bucket 5's chain read from start to end?

Show the answer

The answer is B. All three land in bucket 5 (16 % 11 = 5, 27 % 11 = 5). Every new key goes to the head of the chain, so the last one inserted is at the front: 27, 16, 5.

Can a chained table with M = 11 hold 30 keys?

Show the answer

The answer is B. With chaining the number of buckets is not a limit. With 30 keys α = 30 / 11 ≈ 2.7; the chains hold 2.7 nodes on average and the operations slow down, but the table never fills.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.