Hash table implementation in C
A hash table has an array of buckets. It has a key and value. Key is to find the position of the bucket. Value is to be stored on that location. It can be done by two ways as follows.
- · Using linked list
- · Linear probing
Here, we use linked list to implement the hash table.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//The size of the hash table is defined as 4.
#define SIZE 4
//create a node for hash table. it has a key, value and a
pointer to point the next node
struct h_Node {
int h_key;
int h_value;
struct h_Node*
h_next;
};
// create a hash table
struct h_Node* hashTable[SIZE];
// Hash function to find the hash code
int hashCode(int h_key) {
return h_key %
SIZE;
}
// this function adds the key and value to hash table
void insertIt(int h_key, int h_value) {
int index =
hashCode(h_key);
struct h_Node*
newNode = (struct h_Node*)malloc(sizeof(struct h_Node));
newNode->h_key
= h_key;
newNode->h_value = h_value;
newNode->h_next
= hashTable[index];
hashTable[index] =
newNode;
}
// Display hash table
void displayIt() {
for (int i = 0; i
< SIZE; i++) {
struct h_Node*
temp = hashTable[i];
printf("Bucket %d: ", i);
while (temp) {
printf("(%d, %d) -> ", temp->h_key, temp->h_value);
temp =
temp->h_next;
}
printf("NULL\n");
}
}
int main() {
insertIt(0,27 );
insertIt(2, 30);
insertIt(5, 50);
insertIt(6, 125);
insertIt(3, 45);
displayIt();
return 0;
}
Output:
Compile and run the program to get the output.
Bucket 0: (0, 27) -> NULL
Bucket 1: (5, 50) -> NULL
Bucket 2: (6, 125) -> (2, 30) -> NULL
Bucket 3: (3, 45) -> NULL
Yes. The code is executed Successfully.
This program creates a hash table with some entries and
displayed the data in the buckets. Hope, this code is useful to you. Keep
coding!!!
Comments
Post a Comment