C语言实现哈希表

哈希表

1、哈希表的创建

复制代码
#define MAX 10
#define NULL_KEY -1
typedef int data_type;
typedef struct{
    data_type *ele;
    int n;

}hash_table;

hash_table *create_hash_table(){
hash_table * ht=(hash_table *)malloc(sizeof(hash_table));
ht->n=0;
ht->ele=(data_type *)malloc(sizeof(data_type)*MAX);
for(int i=0;i<MAX;i++){
    ht->ele[i]=NULL_KEY;
}
return ht;
}

2、判满

复制代码
int is_full(hash_table *ht){
    return ht->n==MAX?1:0;
}

3、使用开放地址法解决冲突

复制代码
void insert_hash_table(hash_table *ht,data_type key){
    if(is_full(ht)){
    printf("hash is full\n");
        return;
    }
    int index=key%MAX;
    while(ht->ele[index]!=NULL_KEY){
        index=(index+1)%MAX;
    }
    ht->ele[index]=key;
    ht->n++;
    return;
}

4、查找key

复制代码
int search_hash_key(hash_table *ht,data_type key){
int index=key%MAX;
while(ht->ele[index]!=key){
    index=(index+1)%10;
    //找了一圈没找到,或者找到-1了
    if(index==key%MAX||ht->ele[index]==NULL_KEY){
        return -1;
    }
}
return index;

}

5、遍历哈希表

复制代码
void print_hash(hash_table *ht){
    for(int i=0;i<MAX;i++){
        printf("%d ",ht->ele[i]);
    }
    return;
}

6、使用链地址法

复制代码
#define MAX 7
typedef int data_type;

typedef struct node{
     struct node *next;
     data_type data;
}hash_node;
//二重指针是用来存放指针的地址
//使用指针数组(二重指针)保存
hash_node **create_hash_table(){
    hash_node **ht=(hash_node **)malloc(sizeof(hash_node *)*MAX);
    memset(ht,0,sizeof(hash_node *)*MAX);
    for(int i=0;i<MAX;i++){
        ht[i]=NULL;
    }
    return ht;
}
//插入数据
void insert_hash_data(hash_node **h,data_type key){
    int index=key%MAX;
    hash_node **p=NULL;
    hash_node *temp=NULL;
 

    for(p=&h[index];*p !=NULL;p=&((*p)->next)){
      if((*p)->data>key){
        break;
        }
    }
    temp=(hash_node *)malloc(sizeof(hash_node));
    temp->data=key;
    //*p是前一个节点的next里面存放的地址
    temp->next=*p;
    *p=temp;
   return;

}

void printf_hash_table(hash_node **h){
    int i=0;
    hash_node **p=NULL;
    for(int i=0;i<MAX;i++){
        printf("index=%d :",i);
        for(p=&h[i];*p!=NULL;p=&((*p)->next)){
            printf("%d ",(*p)->data);
        }
        putchar('\n');
    }
    return;
}
相关推荐
小刘要努力呀!2 小时前
嵌入式开发学习(第二阶段 C语言基础)
c语言·学习·算法
joker D8882 小时前
【C++】深入理解 unordered 容器、布隆过滤器与分布式一致性哈希
c++·分布式·哈希算法
草莓熊Lotso2 小时前
【C语言字符函数和字符串函数(一)】--字符分类函数,字符转换函数,strlen,strcpy,strcat函数的使用和模拟实现
c语言·开发语言·经验分享·笔记·其他
小秋学嵌入式-不读研版3 小时前
C42-作业练习
c语言·开发语言·笔记
QQ_4376643144 小时前
Linux下可执行程序的生成和运行详解(编译链接汇编图解)
linux·运维·c语言·汇编·caffe
越城9 小时前
深入理解二叉树:遍历、存储与算法实现
c语言·数据结构·算法
双叶83611 小时前
(C语言)超市管理系统 (正式版)(指针)(数据结构)(清屏操作)(文件读写)
c语言·开发语言·数据结构·c++·windows
序属秋秋秋11 小时前
《数据结构初阶》【二叉树 精选9道OJ练习】
c语言·数据结构·c++·算法·leetcode
欧先生^_^12 小时前
rust语言,与c,go语言一样也是编译成二进制文件吗?
c语言·golang·rust
再睡一夏就好13 小时前
从硬件角度理解“Linux下一切皆文件“,详解用户级缓冲区
linux·服务器·c语言·开发语言·学习笔记