Hash Function In C

[Solved] Hash Function In C | Perl - Code Explorer | yomemimo.com
Question : hashmap c

Answered by : fragile-fly-v68uk7osl9ft

#include <stdio.h>
#include <stdlib.h>
struct node
{ int key; int val; struct node *next;
};
struct table
{ int size; struct node **list;
};
struct table *createTable(int size)
{ struct table *t = (struct table *)malloc(sizeof(struct table)); t->size = size; t->list = (struct node **)malloc(sizeof(struct node *) * size); int i; for (i = 0; i < size; i++) t->list[i] = NULL; return t;
}
int hashCode(struct table *t, int key)
{ if (key < 0) return -(key % t->size); return key % t->size;
}
void insert(struct table *t, int key, int val)
{ int pos = hashCode(t, key); struct node *list = t->list[pos]; struct node *newNode = (struct node *)malloc(sizeof(struct node)); struct node *temp = list; while (temp) { if (temp->key == key) { temp->val = val; return; } temp = temp->next; } newNode->key = key; newNode->val = val; newNode->next = list; t->list[pos] = newNode;
}
int lookup(struct table *t, int key)
{ int pos = hashCode(t, key); struct node *list = t->list[pos]; struct node *temp = list; while (temp) { if (temp->key == key) { return temp->val; } temp = temp->next; } return -1;
}
int main()
{ struct table *t = createTable(5); insert(t, 2, 3); insert(t, 5, 4); printf("%d", lookup(t, 5)); return 0;
}

Source : http://www.kaushikbaruah.com/posts/data-structure-in-c-hashmap/ | Last Update : Thu, 19 Nov 20

Question : hash function in c

Answered by : proud-plover-5bnzuiexc98m

#define CAPACITY 50000 // Size of the Hash Table
unsigned long hash_function(char* str) { unsigned long i = 0; for (int j=0; str[j]; j++) i += str[j]; return i % CAPACITY;
}

Source : | Last Update : Sat, 15 Oct 22

Answers related to hash function in c

Code Explorer Popular Question For Perl