117.info
人生若只如初见

怎么使用c语言实现哈希表

实现哈希表的基本步骤如下:

  1. 定义哈希表的数据结构:包括哈希表大小、桶的数量、桶的结构等。
  2. 实现哈希函数:将键映射到桶的索引。
  3. 实现哈希表的操作函数:包括插入、查找、删除等操作。
  4. 处理冲突:当多个键映射到同一个桶时,需要使用链表、开放寻址等方法来处理冲突。

以下是一个简单的使用C语言实现哈希表的示例代码:

#include 
#include 
#include 

#define TABLE_SIZE 10

typedef struct Node {
    char* key;
    int value;
    struct Node* next;
} Node;

Node* table[TABLE_SIZE];

int hash_function(char* key) {
    int hash = 0;
    for (int i = 0; i < strlen(key); i++) {
        hash += key[i];
    }
    return hash % TABLE_SIZE;
}

void insert(char* key, int value) {
    int index = hash_function(key);
    Node* new_node = (Node*)malloc(sizeof(Node));
    new_node->key = key;
    new_node->value = https://www.yisu.com/ask/value;>next = table[index];
    table[index] = new_node;
}

int search(char* key) {
    int index = hash_function(key);
    Node* current = table[index];
    while (current != NULL) {
        if (strcmp(current->key, key) == 0) {
            return current->value;
        }
        current = current->next;
    }
    return -1; // key not found
}

void delete(char* key) {
    int index = hash_function(key);
    Node* current = table[index];
    Node* prev = NULL;
    while (current != NULL) {
        if (strcmp(current->key, key) == 0) {
            if (prev == NULL) {
                table[index] = current->next;
            } else {
                prev->next = current->next;
            }
            free(current);
            return;
        }
        prev = current;
        current = current->next;
    }
}

int main() {
    insert("apple", 5);
    insert("banana", 10);
    
    printf("Value of apple: %d\n", search("apple"));
    printf("Value of banana: %d\n", search("banana"));
    
    delete("apple");
    
    printf("Value of apple after deletion: %d\n", search("apple"));
    
    return 0;
}

上面的代码实现了一个简单的哈希表,包括插入、查找、删除操作。在这个示例中,哈希函数使用字符的ASCII码之和来计算哈希值,并使用链表处理冲突。你可以根据自己的需求来修改和扩展这个示例。

未经允许不得转载 » 本文链接:https://www.117.info/ask/fe316AzsLAQVTAFM.html

推荐文章

  • c语言怎么将字符串转化为表达式

    在C语言中,可以使用字符串转换函数atoi和atof将字符串转化为表达式。
    如果字符串中的内容是整数,可以使用atoi函数将字符串转换为整数。例如:
    #incl...

  • c语言中split函数的用法是什么

    在C语言中,没有内置的split函数。但是可以通过自定义函数来实现类似的功能。下面是一个示例函数,可以将字符串按照指定的分隔符进行拆分:
    #include #incl...

  • c语言怎么计算某年某月的天数

    在C语言中,可以通过编写函数来计算某年某月的天数。以下是一个示例程序:
    #include int isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) ...

  • 怎么用c语言计算三角形面积

    要计算三角形的面积,需要知道三角形的底和高。假设三角形的底为b,高为h。
    C语言代码如下所示:
    #include int main() { float b, h, area; // 输入三...

  • Jfinal框架启动失败怎么解决

    检查配置文件:首先确保配置文件中的配置项正确设置。比如,检查是否正确配置了数据库连接信息、端口号等。确认配置文件中没有错误或遗漏。 检查依赖:确认项目中...

  • c语言链表的实现原理是什么

    C语言链表的实现原理是通过使用结构体来定义节点,每个节点包含数据和指向下一个节点的指针。通过这种方式,可以动态地创建一个可以存储数据且具有灵活大小的链表...

  • php中imagick的作用是什么

    imagick是一个用于在PHP中处理图像的扩展库。它提供了一组功能丰富的API,可以用于创建、编辑、转换和合成图像。使用imagick可以进行图像大小调整、裁剪、旋转、...

  • java中flink的作用是什么

    Flink是一个流式数据处理框架,其作用是处理和分析实时数据流。它支持事件驱动的应用程序,能够处理大规模数据集,支持复杂的数据转换和分析操作,同时具有高性能...