Search
 
SCRIPT & CODE EXAMPLE
 

C

hashmap c

#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;
}
Comment

PREVIOUS NEXT
Code Example
C :: add field to model rails 
C :: const godot gdscript 
C :: string compare c 
C :: c integer to string 
C :: sdl2 c programming 
C :: hi servicenow 
C :: c style array 
C :: round function in c 
C :: multiplication in c 
C :: xor swap 
C :: vbnet create and write on file 
C :: multiplication table in c using array 
C :: strcmp c 
C :: .sh template 
C :: c radians 
C :: array size in c 
C :: Grepper VSCode Add On 
C :: convert c program to assembly language online 
C :: keep last n bits 
C :: pointers to a function in c 
C :: addition of matrix 
C :: C program for float division of numbers 
C :: c linked list 
C :: declaration in c 
C :: how to arrange a 2d array based on string length in c 
C :: define constant c 
C :: how to print logs when doing unit-testing in rust 
C :: how to take input in c 
C :: string to number in c 
C :: vscode how to output in seperate consile 
ADD CONTENT
Topic
Content
Source link
Name
6+9 =