【数据结构】hash表的功能实现:创建、插入、查找。
hash表功能的实现:创建、插入及查找。
·
问题描述:hash表的功能实现(创建、插入、查找)。
代码实现:
实现顺序遍历需要三个文件(三个文件在同一目录)。
hash.h(定义二叉树)
hash.c(实现接口函数)
main.c(主函数实现)
hash.h
#define N 15
typedef int datatype;
typedef struct node {
datatype key;
datatype value;
struct node * next;
}listnode, *linklist;
typedef struct {
listnode data[N];
}hash;
hash * hash_create();
int hash_insert(hash *HT, datatype key);
linklist * hash_search(hash *HT, datatype key);
hash.c
#include "hash.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
hash * hash_create(){
hash * HT;
if ((HT = (hash *) malloc(sizeof(hash))) == NULL) {
printf("malloc failed\n");
return NULL;
}
memset(HT, 0, sizeof(hash));
return HT;
}
int hash_insert(hash *HT, datatype key){
linklist p, q;
if (HT == NULL) {
printf("HT is NULL\n");
return -1;
}
if ((p = (linklist) malloc(sizeof(listnode))) == NULL) {
printf("malloc failed\n");
return -1;
}
p->key = key;
p->value = key % N;
p->next = NULL;
q = &(HT->data[key % N]);
while (q->next && q->next->key < p->key){
q = q->next;
}
p->next = q->next;
q->next = p;
return 0;
}
linklist * hash_search(hash *HT, datatype key){
linklist p, q;
if (HT == NULL) {
printf("HT is NULL\n");
return NULL;
}
//key % N
p = &(HT->data[key % N]);
while (p->next && p->next->key !=key) {
p = p->next;
}
if (p->next == NULL){
return NULL;
}else {
printf("found\n");
return p->next;
}
}
main.c
#include <stdio.h>
#include "hash.h"
int main(int argc, const char *argv[]) {
hash * HT;
int i;
int key;
linklist r;
int data[] = {23, 34, 46, 16, 68, 15, 7, 31, 26};
if ((HT = hash_create()) == NULL) {
return -1;
}
for (i = 0; i < sizeof(data)/sizeof(int); i++) {
hash_insert(HT, data[i]);
}
printf("input:");
scanf("%d", &key);
r = hash_search(HT, key);
if (r == NULL)
printf("not found\n");
else
printf("found:%d %d\n", key, r->key);
return 0;
}
运行结果:
由上述结果可知:查找23,查找成功。

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)