哈希表基础知识(hash table)(1)

本文深入探讨了散列表的概念、原理与应用,包括常数时间执行的插入、删除和查找操作,以及如何通过分离链接法解决哈希冲突。详细介绍了哈希表的初始化、哈希函数的确定和哈希冲突的解决策略,并通过示例展示了哈希表的基本操作。

本节主要结束散列表的相关内容。。但是那些需要元素间任何排列信息的操作将不会得到有效的支持,比如查找最小值,以线性时间按排序顺序将整个表打印出来的操作都不是散列表所支持的。
针对哈希表,我们需要注意两点,1.哈希函数的确定。本章节用Horner法则来获得哈希函数。2.解决哈希冲突。本章节主要通过分离链接法来解决哈希冲突。
下面是头文件内容

#ifndef hash_h_
#define hash_h_
struct listnode;
typedef struct listnode *Position;
struct Hash_table;
typedef struct Hash_table *Hash;
typedef struct listnode *List;
Hash Init(int tab_size);
int Hash_fun(char * S,int tab_size);
Position Find(char * S,Hash h);
void Insert(char *S,Hash h);
#endif // hash_h_

哈希表的定义以及相应的操作函数:

#include <stdio.h>
#include <stdlib.h>
#include "main.h"
#define min_table_size 100
#include<string.h>
#define  N 100
struct listnode
{
    char * element;
    Position next;
};
struct Hash_table
{
    int tablesize;
    List *thelist;
};
//Init
Hash Init(int tab_size)
{
    if(tab_size<min_table_size)
    {
        printf("error ,the hash is too small\n");
        exit(1);
    }
    Hash h=malloc(sizeof(struct Hash_table));
    h->thelist=malloc(sizeof(List)*tab_size);
    h->tablesize=tab_size;
    int i=0;
    for(;i<tab_size;i++)
    {
        h->thelist[i]=malloc(sizeof(struct listnode));
        h->thelist[i]->next=NULL;
    }
    return h;
}
//Hash_fun
int Hash_fun(char * S,int tab_size)
{
    int Hash_value=0;
    while(*S!='\0')
    {
        Hash_value=Hash_value*32+*S;
        S++;
    }
    return Hash_value % tab_size;
}
//Find
Position Find(char * S,Hash h)
{
    List l=h->thelist[Hash_fun(S,h->tablesize)];
    Position p=l->next;
    while(p!=NULL)
    {
        if(strcmp(S,p->element)==0)
            break;
        p=p->next;
    }
    return p;
}
//Insert
void Insert(char *S,Hash h)
{
    List l=h->thelist[Hash_fun(S,h->tablesize)];
    Position p=Find(S,h);
    if(p==NULL)
    {
        Position p_tem=malloc(sizeof(struct listnode));
        p_tem->element=malloc(sizeof(char)*N);//注意这句话
        strcpy(p_tem->element,S);
        p_tem->next=l->next;
        l->next=p_tem;
    }
}

主函数:

int main()
{
    Hash H_table=Init(297);
    Insert("zhang",H_table);
    Insert("wang",H_table);
    Insert("li",H_table);
    Position p_find=Find("li",H_table);
    printf("%p",p_find);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值