查找和Hash表查找
一、查找
1.基本概念
2.查找方法
(1)顺序查找
(2)折半查找
(3)分块查找
3.总结
二、Hash表查找
1.基本概念
2.Hash表构造方法
保留除数法(常用)
3.处理冲突的方法
(1)开放地址法
(2)链地址法
4.Hash表声明(hash.h)
#ifndef _HASH_H_
#define _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);
#endif
5.Hash表基本运算(hash.c)
(1)创建hash表:hash * hash_create()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hash.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;
}
(2)插入键值:int hash_insert(hash *HT, datatype key)
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;
}
(3)查找键值:linklist hash_search(hash *HT, datatype key)
linklist hash_search(hash *HT, datatype key) {
linklist p;
if (HT == NULL) {
printf("HT is NULL\n");
return NULL;
}
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;
}
}
6.测试函数(test.c)
#include <stdio.h>
#include "hash.h"
int main(int argc, const char *argv[])
{
hash * HT;
int data[] = {23, 34, 14, 38, 46, 16, 68, 15, 7, 31, 26};
int i;
int key;
linklist r;
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;
}