hashmap c

Solutions on MaxInterview for hashmap c by the best coders in the world

showing results for - "hashmap c"
María Fernanda
10 Oct 2020
1#include <stdio.h>
2#include <stdlib.h>
3struct node
4{
5    int key;
6    int val;
7    struct node *next;
8};
9struct table
10{
11    int size;
12    struct node **list;
13};
14struct table *createTable(int size)
15{
16    struct table *t = (struct table *)malloc(sizeof(struct table));
17    t->size = size;
18    t->list = (struct node **)malloc(sizeof(struct node *) * size);
19    int i;
20    for (i = 0; i < size; i++)
21        t->list[i] = NULL;
22    return t;
23}
24int hashCode(struct table *t, int key)
25{
26    if (key < 0)
27        return -(key % t->size);
28    return key % t->size;
29}
30void insert(struct table *t, int key, int val)
31{
32    int pos = hashCode(t, key);
33    struct node *list = t->list[pos];
34    struct node *newNode = (struct node *)malloc(sizeof(struct node));
35    struct node *temp = list;
36    while (temp)
37    {
38        if (temp->key == key)
39        {
40            temp->val = val;
41            return;
42        }
43        temp = temp->next;
44    }
45    newNode->key = key;
46    newNode->val = val;
47    newNode->next = list;
48    t->list[pos] = newNode;
49}
50int lookup(struct table *t, int key)
51{
52    int pos = hashCode(t, key);
53    struct node *list = t->list[pos];
54    struct node *temp = list;
55    while (temp)
56    {
57        if (temp->key == key)
58        {
59            return temp->val;
60        }
61        temp = temp->next;
62    }
63    return -1;
64}
65int main()
66{
67    struct table *t = createTable(5);
68    insert(t, 2, 3);
69    insert(t, 5, 4);
70    printf("%d", lookup(t, 5));
71    return 0;
72}