【问题标题】:How do I iterate and print hashtable in c?如何在 c 中迭代和打印哈希表?
【发布时间】:2018-06-17 23:50:04
【问题描述】:

该实现使用类似于“静态序列列表”的结构(它使用数组来存储元素)。我可以插入和查询 1 个项目。但我需要列出所有项目。

代码:

struct cidade {
    int pkCidade;
    char nomeCidade[50];
};

struct hashCidade {
    int qtdCidade, TABLE_SIZE;
    struct cidade **itensCidade;
};

typedef struct hashCidade HashCidade;

HashCidade *createHashCidade(int TABLE_SIZE);
void releaseHashCidade(HashCidade *ha);
int insertHashCidade(HashCidade *ha, struct cidade CidadeH);
int findHashCidade(HashCidade *ha, char *str, struct cidade *CidadeH);

HashCidade *createHashCidade(int TABLE_SIZE) {
    HashCidade *ha = (HashCidade*)malloc(sizeof(HashCidade));
    if (ha != NULL) {
        int i;
        ha->TABLE_SIZE = TABLE_SIZE;
        ha->itensCidade = (struct cidade **)
                                malloc(TABLE_SIZE * sizeof(struct cidade*));
        if (ha->itensCidade == NULL) {
            free(ha);
            return NULL;
        }
        ha->qtdCidade = 0;
        for (i = 0; i < ha->TABLE_SIZE; i++)
            ha->itensCidade[i] = NULL;
    }
    return ha;
}

void releaseHashCidade(HashCidade *ha) {
    if (ha != NULL) {
        int i;
        for (i = 0; i < ha->TABLE_SIZE; i++) {
            if (ha->itensCidade[i] != NULL)
                free(ha->itensCidade[i]);
        }
        free(ha->itensCidade);
        free(ha);
    }
}

int insertHashCidade(HashCidade *ha, struct cidade CidadeH) {
    if (ha == NULL || ha->qtdCidade == ha->TABLE_SIZE)
        return 0;
    int chave = valorString(CidadeH.nomeCidade);
    int pos = chaveDivisao(chave, ha->TABLE_SIZE);
    struct cidade *nova;
    nova = (struct cidade *)malloc(sizeof(struct cidade));
    if(nova == NULL)
        return 0;
    *nova = CidadeH;
    ha->itensCidade[pos] = nova;
    ha->qtdCidade++;
    return 1;
}

int findHashCidade(HashCidade *ha, char *str, struct cidade *CidadeH) {
    if (ha == NULL)
        return 'n';
    int chave = valorString(str);
    int pos = chaveDivisao(chave, ha->TABLE_SIZE);
    if (ha->itensCidade[pos] == NULL)
        return 0;
    else
        *CidadeH = *(ha->itensCidade[pos]);
    return 1;
}

感谢您的帮助。

【问题讨论】:

  • 您必须分配一个struct cidade,对其进行初始化,并在适当的位置为其分配一个指针。哦,对于打印:遍历数组,对于每个条目:遍历列表。

标签: c hashtable


【解决方案1】:

在我看来,您可以遍历哈希数组中的非 NULL 指针并打印相应的结构详细信息:

void printCidade(const struct cidade *cp) {
    printf("%s\n", cp->nomeCidade);
}

void printHashCidade(const HashCidade *ha) {
    if (ha != NULL) {
        int i;
        for (i = 0; i < ha->TABLE_SIZE; i++) {
            if (ha->itensCidade[i] != NULL)
                printCidade(ha->itensCidade[i]);
        }
    }
}

【讨论】:

  • @AdalbertoJoséBrasaca:很高兴为您提供帮助。支持答案是在stackoverflow上表示感谢的标准方式:)
猜你喜欢
  • 2015-07-16
  • 2021-12-25
  • 2023-04-07
  • 1970-01-01
  • 2016-11-01
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 2012-10-23
相关资源
最近更新 更多