-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_hash_table.c
More file actions
92 lines (82 loc) · 2.56 KB
/
simple_hash_table.c
File metadata and controls
92 lines (82 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include <string.h>
#include "simple_hash_table.h"
#include "ktmem.h"
unsigned int hash_function2(const char *str) {
unsigned int hash = 5381;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c;
}
return hash % TABLE_SIZE;
}
hash_table_t* create_table() {
hash_table_t *hashTable = (hash_table_t *)ktmalloc(sizeof(hash_table_t));
hashTable->table = (hash_node_t **)calloc(TABLE_SIZE, sizeof(hash_node_t *));
for (int i = 0; i < TABLE_SIZE; i++){
hashTable->table[i] = NULL;
}
hashTable->size = 0;
hashTable->capacity = TABLE_SIZE;
return hashTable;
}
hash_node_t* create_node(const char *key, int frequency) {
hash_node_t *newNode = malloc(sizeof(hash_node_t));
newNode->key = strdup(key);
newNode->frequency = frequency;
newNode->next = NULL;
return newNode;
}
void insert(hash_table_t *hashTable, const char *key) {
unsigned int index = hash_function2(key);
hash_node_t *newNode = create_node(key, 1);
if (hashTable->table[index] == NULL) {
hashTable->table[index] = newNode;
hashTable->size++;
} else {
hash_node_t *current = hashTable->table[index];
hash_node_t *prev = NULL;
while (current != NULL && strcmp(current->key, key) != 0) {
prev = current;
current = current->next;
}
if (current == NULL) {
prev->next = newNode;
hashTable->size++;
} else {
current->frequency++;
free(newNode->key);
free(newNode);
}
}
}
int get_frequency(hash_table_t *hashTable, const char *key) {
unsigned int index = hash_function2(key);
hash_node_t *current = hashTable->table[index];
while (current != NULL && strcmp(current->key, key) != 0) {
current = current->next;
}
return current ? current->frequency : 0;
}
void free_table(hash_table_t *hashTable) {
for (int i = 0; i < TABLE_SIZE; i++) {
hash_node_t *current = hashTable->table[i];
while (current != NULL) {
hash_node_t *temp = current;
current = current->next;
free(temp->key);
free(temp);
}
}
free(hashTable->table);
free(hashTable);
}
void print_frequencies(hash_table_t *hashTable) {
for (int i = 0; i < TABLE_SIZE; i++) {
hash_node_t *current = hashTable->table[i];
while (current != NULL) {
printf("Character: %s, Frequency: %d\n", current->key, current->frequency);
current = current->next;
}
}
}