Amazonでお得にショッピング! 特典を見る(Amazon)→

C Program To Implement Dictionary Using Hashing Algorithms

// 5. Cleanup void free_dictionary(Dictionary *dict) for (int i = 0; i < dict->size; i++) KeyValue *current = dict->table[i]; while (current != NULL) KeyValue *temp = current; current = current->next; free(temp->key); free(temp);

destroy_table(dict); return 0;

// --- Data Structures ---

Here is a working example that ties everything together:

Without hashing, we might use an array of key‑value pairs and linear search – O(n) per operation. With a balanced binary search tree we get O(log n). Hashing improves this to by computing an index directly from the key. c program to implement dictionary using hashing algorithms

#include <stdio.h> #include <stdlib.h> #include <string.h>

Hashing allows us to achieve average O(1) time complexity for insertions, searches, and deletions by mapping keys to indices in an array. We will cover the underlying theory of hash functions, collision resolution strategies, and provide a fully working C program that uses (linked lists) to handle collisions. The program will support strings as keys and integers as values, but the design can be easily adapted to other data types. Hashing improves this to by computing an index

#include #include #include #define TABLE_SIZE 10007 // A prime number minimizes clustering // Define the structure for a dictionary node typedef struct DictNode char *key; int value; struct DictNode *next; DictNode; // Define the Hash Table structure typedef struct DictNode *buckets[TABLE_SIZE]; Dictionary; // DJB2 Hashing Algorithm unsigned int hash_function(const char *key) unsigned long hash = 5381; int c; while ((c = *key++)) hash = ((hash << 5) + hash) + c; // hash * 33 + c return hash % TABLE_SIZE; // Initialize the dictionary Dictionary* create_dictionary() Dictionary *dict = (Dictionary*)malloc(sizeof(Dictionary)); if (!dict) perror("Failed to allocate memory for dictionary"); exit(EXIT_FAILURE); for (int i = 0; i < TABLE_SIZE; i++) dict->buckets[i] = NULL; return dict; // Insert or update a key-value pair void dict_insert(Dictionary *dict, const char *key, int value) unsigned int index = hash_function(key); DictNode *current = dict->buckets[index]; // Check if the key already exists to update its value while (current != NULL) if (strcmp(current->key, key) == 0) current->value = value; return; current = current->next; // Key does not exist, create a new node DictNode *new_node = (DictNode*)malloc(sizeof(DictNode)); if (!new_node) perror("Failed to allocate memory for node"); exit(EXIT_FAILURE); new_node->key = strdup(key); // Duplicate string to ensure ownership new_node->value = value; // Insert at the beginning of the chain (O(1) insertion) new_node->next = dict->buckets[index]; dict->buckets[index] = new_node; // Search for a value by key // Returns 1 if found and updates the value pointer, 0 otherwise int dict_search(Dictionary *dict, const char *key, int *found_value) unsigned int index = hash_function(key); DictNode *current = dict->buckets[index]; while (current != NULL) if (strcmp(current->key, key) == 0) *found_value = current->value; return 1; // Success current = current->next; return 0; // Not found // Delete a key-value pair from the dictionary int dict_delete(Dictionary *dict, const char *key) unsigned int index = hash_function(key); DictNode *current = dict->buckets[index]; DictNode *prev = NULL; while (current != NULL) if (strcmp(current->key, key) == 0) if (prev == NULL) // Node to delete is the head of the chain dict->buckets[index] = current->next; else // Node to delete is in the middle or end prev->next = current->next; free(current->key); free(current); return 1; // Deleted successfully prev = current; current = current->next; return 0; // Key not found // Free all memory allocated for the dictionary void free_dictionary(Dictionary *dict) for (int i = 0; i < TABLE_SIZE; i++) DictNode *current = dict->buckets[i]; while (current != NULL) DictNode *temp = current; current = current->next; free(temp->key); free(temp); free(dict); // Driver program to demonstrate functionality int main() Dictionary *my_dict = create_dictionary(); // Inserting pairs dict_insert(my_dict, "alice", 25); dict_insert(my_dict, "bob", 30); dict_insert(my_dict, "charlie", 35); // Updating an existing key dict_insert(my_dict, "alice", 26); // Searching items int value; if (dict_search(my_dict, "alice", &value)) printf("Found 'alice' with value: %d\n", value); else printf("'alice' not found.\n"); if (dict_search(my_dict, "unknown", &value)) printf("Found 'unknown' with value: %d\n", value); else printf("'unknown' not found.\n"); // Deleting an item if (dict_delete(my_dict, "bob")) printf("Deleted 'bob' successfully.\n"); // Confirming deletion if (!dict_search(my_dict, "bob", &value)) printf("'bob' is no longer in the dictionary.\n"); // Clean up memory free_dictionary(my_dict); return 0; Use code with caution. Technical Breakdown of Operations 1. Collision Handling Strategy

// 6. Utility: Print Dictionary void print_dictionary(Dictionary *dict) printf("\n--- Dictionary Contents ---\n"); for (int i = 0; i < dict->size; i++) KeyValue *current = dict->table[i]; if (current != NULL) printf("Index [%d]: ", i); while (current != NULL) printf("(%s: %d) -> ", current->key, current->value); current = current->next; The program will support strings as keys and

A dictionary maps unique keys to specific values. To implement this using hashing, the architecture requires three core components:

int main() Dictionary myDict = 0 ; // Initialize buckets to NULL insert(&myDict, "Apple" , "A sweet red fruit" ); insert(&myDict, "C" , "A powerful programming language" ); char *result = search(&myDict, "Apple" ); if (result) printf( "Apple: %s\n" , result); return 0 ; Use code with caution. Copied to clipboard Quick Way to Implement Dictionary in C - Stack Overflow

もくじ