理解哈希表,就是先生成一 临时数组,用于存放全部待检测数的值,再创造一函数,关联待检测数与临时数组的每一元素的下标。
查询时根据关联函数用待检测数推算出临时函数的下标值,再读出此下标的元素值。这样就省去了遍历待检测数组的时间。
哈希表简单地理解为,一次扫描,永久使用。
用数组作为临时数组
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int main(void) {/* typedef struct node {int data;struct node *next;}HASH;*/int zhi[3]={1,2,3}; //待检测数组 int *ha=malloc(10000*4); //临时数组,可以存放10000个地址for(int a=0;a<3;a++){ //扫描目标数组zhi,一次生成键值对,存在ha数组中int key=zhi[a]+1; //哈希函数,把目标数与key关联ha[key]=zhi[a]; }//查询int o=3; //查询3是否存在int key1=o+1; //哈希关联函数printf("%d\n",ha[key1]); //这样就不用遍历zhi[]数组free(ha);return 0;
}
用struct 作为临时数组
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int main(void) {typedef struct node {int data;struct node *next;}HASH;int zhi[3]={1,2,3}; //扫描目标数组zhi一次生成ha键值对ha数组HASH ha[20]={};for(int a=0;a<3;a++){int key=zhi[a]+1; //哈希函数,把目标数与key关联ha[key].data=zhi[a]; }//查询int o=3; //查询3是否存在int key1=o+1; //哈希关联函数printf("%d\n",ha[key1].data); //这样就不用遍历zhi[]数组return 0;
}
这种加减乘除,求余数,取数值几位的函数方法只适用于数值如int数组。遇到字符串如待检测是中文名字就不能用此方法创建关联函数。