Last active
April 24, 2022 10:22
-
-
Save piusayowale/c1b504e3421888adc698f9c563895d9d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
#include <string.h> | |
typedef struct { | |
int is_free; | |
uint32_t key; | |
char value[10]; | |
}bin; | |
typedef struct { | |
bin* table; | |
uint32_t size; | |
}hashTable; | |
hashTable * init_table(int size) { | |
hashTable* table = (hashTable*)malloc(sizeof (hashTable)); | |
if (table == NULL) { | |
return NULL; | |
} | |
table->table = (bin*)malloc(sizeof(bin) * size); | |
if (table->table == NULL) { | |
return NULL; | |
} | |
for (int i = 0; i < size; i++) { | |
bin* bin = &table->table[i]; | |
bin->is_free = 1; | |
} | |
table->size = size; | |
return table; | |
} | |
void insert(hashTable* table, int key, char * data) { | |
int index = key % table->size; | |
bin *table_item = &table->table[index]; | |
if (table_item->is_free == 1) { | |
table_item->key = key; | |
table_item->is_free = 0; | |
memset(table_item->value, '\0', sizeof table_item->value); | |
memcpy(table_item->value, data, strlen(data)); | |
} | |
else { | |
printf("Failed"); | |
} | |
return; | |
} | |
char* getItem(hashTable * table, int key) { | |
int index = key % table->size; | |
bin* b = &table->table[index]; | |
if (b->is_free == 1) { | |
return "Empty\n"; | |
} | |
return b->value; | |
} | |
int main() | |
{ | |
hashTable* table = init_table(5); | |
insert(table, 6, "Pius\n"); | |
insert(table, 8, "Paul\n"); | |
insert(table, 9, "Tolu\n"); | |
printf(getItem(table, 9)); | |
printf(getItem(table, 5)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment