This commit is contained in:
krahets
2023-10-18 02:16:55 +08:00
parent 64c5d13051
commit d2ba55fcd6
22 changed files with 374 additions and 436 deletions

View File

@@ -1405,39 +1405,35 @@ index = hash(key) % capacity
```c title="array_hash_map.c"
/* 键值对 int->string */
struct pair {
typedef struct {
int key;
char *val;
};
typedef struct pair pair;
} Pair;
/* 基于数组简易实现的哈希表 */
struct arrayHashMap {
pair *buckets[HASH_MAP_DEFAULT_SIZE];
};
typedef struct arrayHashMap arrayHashMap;
typedef struct {
Pair *buckets[HASH_MAP_DEFAULT_SIZE];
} ArrayHashMap;
/* 哈希表初始化函数 */
arrayHashMap *newArrayHashMap() {
arrayHashMap *map = malloc(sizeof(arrayHashMap));
ArrayHashMap *newArrayHashMap() {
ArrayHashMap *map = malloc(sizeof(ArrayHashMap));
return map;
}
/* 添加操作 */
void put(arrayHashMap *d, const int key, const char *val) {
pair *pair = malloc(sizeof(pair));
pair->key = key;
pair->val = malloc(strlen(val) + 1);
strcpy(pair->val, val);
void put(ArrayHashMap *d, const int key, const char *val) {
Pair *Pair = malloc(sizeof(Pair));
Pair->key = key;
Pair->val = malloc(strlen(val) + 1);
strcpy(Pair->val, val);
int index = hashFunc(key);
d->buckets[index] = pair;
d->buckets[index] = Pair;
}
/* 删除操作 */
void removeItem(arrayHashMap *d, const int key) {
void removeItem(ArrayHashMap *d, const int key) {
int index = hashFunc(key);
free(d->buckets[index]->val);
free(d->buckets[index]);
@@ -1445,8 +1441,8 @@ index = hash(key) % capacity
}
/* 获取所有键值对 */
void pairSet(arrayHashMap *d, mapSet *set) {
pair *entries;
void pairSet(ArrayHashMap *d, MapSet *set) {
Pair *entries;
int i = 0, index = 0;
int total = 0;
@@ -1457,7 +1453,7 @@ index = hash(key) % capacity
}
}
entries = malloc(sizeof(pair) * total);
entries = malloc(sizeof(Pair) * total);
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
entries[index].key = d->buckets[i]->key;
@@ -1472,7 +1468,7 @@ index = hash(key) % capacity
}
/* 获取所有键 */
void keySet(arrayHashMap *d, mapSet *set) {
void keySet(ArrayHashMap *d, MapSet *set) {
int *keys;
int i = 0, index = 0;
int total = 0;
@@ -1497,7 +1493,7 @@ index = hash(key) % capacity
}
/* 获取所有值 */
void valueSet(arrayHashMap *d, mapSet *set) {
void valueSet(ArrayHashMap *d, MapSet *set) {
char **vals;
int i = 0, index = 0;
int total = 0;
@@ -1522,11 +1518,11 @@ index = hash(key) % capacity
}
/* 打印哈希表 */
void print(arrayHashMap *d) {
void print(ArrayHashMap *d) {
int i;
mapSet set;
MapSet set;
pairSet(d, &set);
pair *entries = (pair *)set.set;
Pair *entries = (Pair *)set.set;
for (i = 0; i < set.len; i++) {
printf("%d -> %s\n", entries[i].key, entries[i].val);
}