Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define NUMBER_OF_BUCKETS 3
- typedef struct _node {
- char* key;
- void* value; // Most hash tables have a value in each node too
- struct _node* next;
- } NODE, *PNODE;
- // Create an unattached node and initialize it
- PNODE create_node(char* key, void* value) {
- PNODE pnode = (PNODE)malloc(sizeof (NODE));
- pnode->key = strdup(key);
- pnode->value = value;
- pnode->next = NULL;
- return pnode;
- }
- // Destroy a dynamically allocated node
- PNODE destroy_node(PNODE pnode) {
- if (pnode) {
- if (pnode->key) free(pnode->key);
- free(pnode);
- }
- }
- // Simple hashing function
- // (Sum of character codes in key, modulo # of buckets)
- int calc_hash(char* key) {
- int bucket = 0;
- while (*key) {
- bucket += (int)(*key);
- key++;
- }
- return (bucket % NUMBER_OF_BUCKETS);
- }
- // Insert dynamic node into table
- // NOTE: Static nodes will seg fault during cleanup
- void insert_node(PNODE* table, PNODE pnode) {
- int bucket = calc_hash(pnode->key);
- pnode->next = table[bucket];
- table[bucket] = pnode;
- }
- // Returns node ptr, or NULL if not found
- PNODE find_node(PNODE* table, char* key) {
- int bucket = calc_hash(key);
- PNODE pnode = table[bucket];
- while (pnode) {
- if (strcmp(pnode->key, key) ==0) return pnode;
- pnode = pnode->next;
- }
- // Not found
- return NULL;
- }
- // Locate node by key, then print key if found
- void print_node(PNODE* table, char* key) {
- PNODE pnode = find_node(table, key);
- if (pnode) {
- printf("Found: %s\n", key);
- } else {
- printf("Not found: %s\n", key);
- }
- }
- // Walk the entire table and print all found nodes
- void print_all_nodes(PNODE* table) {
- for (int bucket=0; bucket<NUMBER_OF_BUCKETS; bucket++) {
- PNODE pnode = table[bucket];
- while (pnode) {
- printf("Found %s\n", pnode->key);
- pnode = pnode->next;
- }
- }
- }
- // Deallocate all nodes in the table
- void destroy_all_nodes(PNODE* table) {
- for (int bucket=0; bucket<NUMBER_OF_BUCKETS; bucket++) {
- PNODE pnode = table[bucket];
- if (pnode) {
- while (pnode->next) {
- PNODE pnext = pnode->next;
- pnode->next = pnode->next->next;
- destroy_node(pnext);
- }
- destroy_node(pnode);
- table[bucket] = NULL;
- }
- }
- }
- int main(void) {
- PNODE table[NUMBER_OF_BUCKETS];
- // Clear the table!
- memset(table, 0, NUMBER_OF_BUCKETS * sizeof (PNODE));
- PNODE pnode = create_node("Anant", NULL);
- insert_node(table, pnode);
- pnode = create_node("Param", NULL);
- insert_node(table, pnode);
- pnode = create_node("Heisenberg", NULL);
- insert_node(table, pnode);
- // What have we got?
- print_all_nodes(table);
- // Clean up dynamic memory
- destroy_all_nodes(table);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement