Menu
Coddy logo textTech

put

Lección 5 de 14 del curso Tablas Hash - Serie de Estructuras de Datos #4 de Coddy.

challenge icon

Desafío

Fácil

Agrega un método put a la clase HashMap.

Recibe un entero key y un entero value, y almacena el par en la tabla:

  • Si la clave ya existe, actualiza su valor.
  • De lo contrario, agrega un nuevo par [key, value] al bucket correspondiente e incrementa count.

Pruébalo tú mismo

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

Todas las lecciones de Tablas Hash - Serie de Estructuras de Datos #4