-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.c
More file actions
35 lines (31 loc) · 797 Bytes
/
HashTable.c
File metadata and controls
35 lines (31 loc) · 797 Bytes
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
// Copyright 2024 JOK Inc. All Rights Reserved.
// Author: easytojoin@163.com (jok)
#include "HashTable.h"
static u_int32_t cal_hash(const char* key) {
u_int32_t hash = 0;
const char* ptr = key;
while (*ptr) {
hash += *ptr++;
}
return hash % HASH_TABLE_SIZE;
}
void insert(HashTable* table, const char* key, int val) {
u_int32_t hash = cal_hash(key);
Node* node = (Node*)malloc(sizeof(Node));
strcpy(node->key, key);
node->val = val;
node->next = table->table[hash];
table->table[hash] = node;
}
int search(HashTable* table, const char* key, int* val) {
u_int32_t hash = cal_hash(key);
Node* node = table->table[hash];
while (node) {
if (strcmp(node->key, key) == 0) {
*val = node->val;
return 0;
}
node = node->next;
}
return -1;
}