Menu
Coddy logo textTech

put

Coddy의 Hash Table - 자료구조 시리즈 #4 코스 레슨 — 14개 중 5번째.

challenge icon

챌린지

쉬움

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;
}

Hash Table - 자료구조 시리즈 #4의 모든 레슨