繁体   English   中英

Hash 表与 C 中的链接

[英]Hash table with chaining in C

I write code in C for hash table but I want use the hash table with chaining but I don't know how, is there any article or someone can help me how to use hash table with chaining in c?

我的代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char hashTable[26][100];

void printHashTable(){
    int i;
    printf("HASHTABLE\n");
    for(i=0;i<26;i++){
        printf("[%02d] - %s\n", i, hashTable[i]);
    }
}

void menu(){
    printf("\n\nMenu\n");
    printf("1. Input new string\n");
    printf("2. Exit\n");
}

int hash(char s[100]){
    int len = strlen(s); 
    int i;
    int sum = 0;
    for(i=0;i<len;i++){
        sum += s[i];
    }
    printf("sum = %d\n", sum);
    getchar();
    return sum % 26;
}

void insertToHashTable(int index, char s[100]){
    if(strcmp(hashTable[index],"") == 0){
        strcpy(hashTable[index], s);
    }else{
        int i;
        for(i=index+1;i<26;i++){
            if(strcmp(hashTable[i], "")==0){
                strcpy(hashTable[i], s);
                break;
            }   
        }
    }
}

int main(){
    int choice = 0;
    char s[100];
    int index;
    do{
        system("cls");
        printHashTable();
        menu();
        printf("Input choice = ");
        scanf("%d", &choice); getchar();
        if(choice == 1){
            printf("Input string: ");
            scanf("%[^\n]", s); getchar();
            index = hash(s);
            insertToHashTable(index, s);
        }
    }while(choice!=2);
    return 0;
}

但是为了使您的结构更加动态,让我们将您的 hash 表声明更新为:

struct hash_table_node
{
   char* value;
   hash_table_node* next;
};

hash_table_node* hashTable[26];

所以每个hash_table_node都是一个指向字符串和链中“下一个”节点的指针。

然后您的插入 function 变得简单,但它确实需要为节点和要复制到其中的字符串分配 memory。

void insertToHashTable(int index, const char* s) {

    hash_table_node* node = malloc(sizeof(hash_table_node)); 
 
    node->value = (char*)malloc(strlen(s) + 1);
    strcpy(node->value, s);

    node->next = hashTable[index]; // insert the new string to the front of the linked list
    hashTable[index] = node;
}

然后您的 printHashTable function 可以更新如下:

void printHashTable(){
    int i;
    printf("HASHTABLE\n");
    for(i=0;i<26;i++){
        printf("Nodes in slot: %d:\n", i);
        hash_table_node* node = hashTable[i];
        while (node)
        {
           printf("%s\n", node->value);
           node = node->next;
        }
    }
}

未显示,但留给您作为练习:

  • 您可能需要更新hash以将const char* s作为参数而不是s[100] 但是您不需要更改此功能中的代码。

  • 插入 function 不会检查要添加的字符串是否已经在表中。

  • 从表中删除元素并使用适当的调用从插入 function 中free分配的 memory

  • 一次删除所有元素以重置 hash 表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM