放入
Coddy 哈希表:数据结构系列第 4 讲 课程的第 5 课,共 14 课。
挑战
简单为 HashMap 类添加一个 put 方法。
它接收一个整数 key 和一个整数 value,并将这对值存储在表中:
- 如果键已存在,则更新它的值。
- 否则,将新的
[key, value]对添加到相应的桶中,并递增count。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hashmap.h"
int main() {
HashMap h;
HashMap_init(&h);
char line[256];
while (fgets(line, sizeof(line), stdin)) {
line[strcspn(line, "\r\n")] = '\0';
char* cmd = strtok(line, " \t");
if (!cmd) continue;
if (strcmp(cmd, "state") == 0) { printf("%d %d %d\n", h.capacity, h.capacity, h.count); }
if (strcmp(cmd, "hash") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%d\n", HashMap_hash(&h, atoi(arg))); }
if (strcmp(cmd, "put") == 0) { char* a = strtok(NULL, " \t"); char* b = strtok(NULL, " \t"); if (a && b) HashMap_put(&h, atoi(a), atoi(b)); }
if (strcmp(cmd, "bucketSize") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%d\n", h.buckets[atoi(arg)].size); }
if (strcmp(cmd, "count") == 0) { printf("%d\n", h.count); }
}
return 0;
}
哈希表:数据结构系列第 4 讲中的所有课
自己练习: C 在线编译器