c 哈希表

理解哈希表,就是先生成一 临时数组,用于存放全部待检测数的值,再创造一函数,关联待检测数与临时数组的每一元素的下标。

查询时根据关联函数用待检测数推算出临时函数的下标值,再读出此下标的元素值。这样就省去了遍历待检测数组的时间。

 

哈希表简单地理解为,一次扫描,永久使用。

用数组作为临时数组


#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数组。遇到字符串如待检测是中文名字就不能用此方法创建关联函数。

 

 

 

 

 

 

 

相关推荐

  1. c

    2024-04-23 09:44:02       35 阅读
  2. C#中的(Hashtable)

    2024-04-23 09:44:02       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 09:44:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 09:44:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 09:44:02       82 阅读
  4. Python语言-面向对象

    2024-04-23 09:44:02       91 阅读

热门阅读

  1. 【ChatGPT】【Gemini】-用Python调用google的Gemini API

    2024-04-23 09:44:02       37 阅读
  2. 在终端使用DOCKER部署ollama

    2024-04-23 09:44:02       38 阅读
  3. WPF之自定义控件模版

    2024-04-23 09:44:02       30 阅读
  4. 【软件测试】白盒测试White box testing

    2024-04-23 09:44:02       32 阅读
  5. PaddleSeg(1)配置文件详解

    2024-04-23 09:44:02       30 阅读
  6. Mockito

    Mockito

    2024-04-23 09:44:02      27 阅读
  7. 华为od机试真题——找磨损度最高和最低的硬盘

    2024-04-23 09:44:02       31 阅读
  8. oracle11g集群挂起

    2024-04-23 09:44:02       29 阅读
  9. .Net4.0 Web.config 配置实践

    2024-04-23 09:44:02       38 阅读
  10. Apache Spark 的基本概念和在大数据分析中的应用

    2024-04-23 09:44:02       34 阅读