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;
}
相关推荐
速易达网络4 小时前
C语言常见推理题
java·c语言·算法
沪漂的码农4 小时前
C语言队列与链表结合应用完整指南
c语言·链表
小龙报6 小时前
《算法通关指南:算法基础篇 --- 一维前缀和 — 1. 【模板】一维前缀和,2.最大子段和》
c语言·数据结构·c++·算法·职场和发展·创业创新·visual studio
R6bandito_6 小时前
STM32 HAL库原子操作编译问题解决指南
c语言·ide·经验分享·stm32·单片机·嵌入式硬件·mcu
树在风中摇曳6 小时前
LeetCode 1658 | 将 x 减到 0 的最小操作数(C语言滑动窗口解法)
c语言·算法·leetcode
degen_7 小时前
BDS 执行平台相关动作
c语言·笔记·bios
乾 乾7 小时前
VSCode 设置中文
c语言
小柯博客8 小时前
STM32MP1 没有硬件编解码,如何用 CPU 实现 H.264 编码支持 WebRTC?
c语言·stm32·嵌入式硬件·webrtc·h.264·h264·v4l2
铅笔小新z8 小时前
深入理解C语言内存管理:从栈、堆到内存泄露与悬空指针
c语言·开发语言
散峰而望19 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github