学堂 学堂 学堂公众号手机端

实现哈希表的基本步骤如下: 定义哈希表的数据结构:包括哈希表大小、桶的数量、桶的结构等

lewis 1年前 (2024-03-01) 阅读数 5 #技术

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

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

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

#include<stdio.h> #include<stdlib.h> #include<string.h> #defineTABLE_SIZE10 typedefstructNode{ char*key; intvalue; structNode*next; }Node; Node*table[TABLE_SIZE]; inthash_function(char*key){ inthash=0; for(inti=0;i<strlen(key);i++){ hash+=key[i]; } returnhash%TABLE_SIZE; } voidinsert(char*key,intvalue){ intindex=hash_function(key); Node*new_node=(Node*)malloc(sizeof(Node)); new_node->key=key; new_node->value=value; new_node->next=table[index]; table[index]=new_node; } intsearch(char*key){ intindex=hash_function(key); Node*current=table[index]; while(current!=NULL){ if(strcmp(current->key,key)==0){ returncurrent->value; } current=current->next; } return-1;//keynotfound } voiddelete(char*key){ intindex=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; } } intmain(){ insert("apple",5); insert("banana",10); printf("Valueofapple:%d\n",search("apple")); printf("Valueofbanana:%d\n",search("banana")); delete("apple"); printf("Valueofappleafterdeletion:%d\n",search("apple")); return0; }

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


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门