首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在c中迭代和打印hashtable?

如何在c中迭代和打印hashtable?
EN

Stack Overflow用户
提问于 2018-06-17 23:50:04
回答 1查看 2.7K关注 0票数 0

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

守则:

代码语言:javascript
复制
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;
}

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-18 00:10:56

在我看来,您只需遍历哈希数组中的非NULL指针,并打印相应的结构细节:

代码语言:javascript
复制
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]);
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50901329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档