栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

散列(哈希)表的C语言简单(创建,插入)实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

散列(哈希)表的C语言简单(创建,插入)实现

#include
#include
#define A 1000

struct listnode{
    char element;
    struct listnode* next;
}H[A];                      //直接用数组
typedef struct listnode list;

int Hash(const char* key,int a){
    unsigned int hashnum=0;
    while(*key!=''){
        hashnum=hashnum+*key++;   
    }
    return hashnum%a;
}                          //哈希函数     


void Intital(list* H){
    for(int i=0;i<1000;i++){
        H[i].next=NULL;
    }
}                               //初始化

list* Find(list*H,const char* key){
    list p;
    list* l;
    p=H[Hash(key,A)];
    l=p.next;
    while(l!=NULL && l->element!=*key){
        l=l->next;
    }
    return l;
}            //查找数据

void Insert(list* H,const char* key){
    list* p=Find(H,key);
    if(p==NULL){
        list* m=(list*)malloc(sizeof(list));
        m->element=*key;
        m->next=H[Hash(key,A)].next;
        H[Hash(key,A)].next=m;
    }
}             //插入(分离链表法)

int main(void){
    Intital(H);
    Insert(H,"a");
    Insert(H,"c");
    printf("%cn",Find(H,"a")->element);
    printf("%cn",Find(H,"c")->element);
} 

    另一种形式

#include
#include
#define A 1000

struct listnode{
	char element;
	struct listnode* next;
};
typedef struct listnode* list;

struct hash{
	list *Thelist; 
};
typedef struct hash *Hashtbl;

int Hash(const char* key,int a){
	unsigned int hashnum=0;
	while(*key!=''){
		hashnum=hashnum+*key++; 
	}
	return hashnum%a;
} 

Hashtbl Intital(){
	Hashtbl H=(Hashtbl)malloc(sizeof(struct hash));
	H->Thelist=(list*)malloc(sizeof(list)*A);
	for(int i=0;iThelist[i]=(list)malloc(sizeof(struct listnode));
		H->Thelist[i]->next=NULL;
	}
	return H;
}

list Find(Hashtbl H,const char* key){
	list p,l;
	p=H->Thelist[Hash(key,A)];
	l=p->next;
	while(l!=NULL && l->element!=*key){
		l=l->next;
	}
	return l;
}

Hashtbl Insert(Hashtbl H,const char* key){
	list p=Find(H,key);
	if(p==NULL){
		list m=(list)malloc(sizeof(struct listnode));
		m->element=*key;
		m->next=H->Thelist[Hash(key,A)]->next;
		H->Thelist[Hash(key,A)]->next=m;
	}
	return H;
}

int main(void){
	Hashtbl H=Intital();
	H=Insert(H,"a");
	H=Insert(H,"c");
	printf("%cn",Find(H,"a")->element);
	printf("%cn",Find(H,"c")->element);
} 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/347985.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号