哈希表

哈希表:
使用哈希函数将任意类型的数据映射为整型值
在这里插入图片描述
比如val % size这个函数,(处理冲突)如下图所示:
在这里插入图片描述
处理冲突的四大类操作:
1.开放定址法
2.拉链法
3.再哈希
4.建立公共溢出区(存储产生冲突的值的索引)
Leetcode题:
在这里插入图片描述
代码实现:

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

typedef struct Node{
    char *str;
    struct Node *next;
}Node;

typedef struct HashTable{
    Node **data;
    int size;
}HashTable;

Node *init_node(char *s, Node *head){
    Node *p = (Node *)malloc(sizeof(Node));
    p->str = strdup(s);//使用头插法
    p->next = head;
    return p;
}

HashTable *init_table(int n){
    HashTable *h = (HashTable *)malloc(sizeof(HashTable));
    h->size = n << 1;
    h->data = (Node **)calloc(h->size, sizeof(Node *));
    return h;
}

int BKDRHash(char *s){
    int seed = 31, hash = 0;
    for(int i = 0; s[i]; i++) hash = hash * seed + s[i];
    return hash & 0x7fffffff;
}

int insert(HashTable *h, char *str){
    int hash = BKDRHash(str);
    int ind = hash % h->size;
    h->data[ind] = init_node(str, h->data[ind]);
    return 1;
}

int search(HashTable *h, char *str){
    int hash = BKDRHash(str);
    int ind = hash % h->size;
    Node *p = h->data[ind];
    while(p && strcmp(p->str, str)) p = p->next;
    return p != NULL;
}

void clear_node(Node *node){
    if(node == NULL) return;
    Node *p = node, *q;
    while(p){
        q = p->next;
        free(p->str);
        free(p);
        p = q;
    }
    free(q);
    return;
}

void clear_table(HashTable *h){
    if(h == NULL) return;
    for(int i = 0; i < h->size; i++) clear_node(h->data[i]);
    free(h->data);
    free(h);
    return;
}

int main(){
    int op;
    #define max_n 100
    char str[max_n + 5];
    HashTable *h = init_table(max_n + 5);
    while(~scanf("%d%s", &op, str)){
        switch (op){
            case 0:
                printf("insert %s to hash table\n", str);
                insert(h, str);
                break;
            case 1:
                printf("search %s from hash table result = %d\n", str, search(h, str));
                break;
            }
        }
    clear_table(h);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值