其他分享
首页 > 其他分享> > 哈希表线性探测(功能:查找,删除,插入)

哈希表线性探测(功能:查找,删除,插入)

作者:互联网

直接看代码:

#include <stdio.h>
#include <stdlib.h>
//宏定义相关常量
#define Max  10
#define Size  10

typedef struct Sqlist{
int *data;
int length;//长度
}Sqlist;//顺序表

typedef struct HashSqlist{
int *data;
int length;
}HashSqlist;//哈希表

int hash (int key){
return key%10;
}  //哈希函数

void InitSqlist(Sqlist &l){ //这里l 还没定义,所以要加 &
printf("Please int the length of the hashTable\n");
scanf("%d",&l.length);
l.data = (int *)malloc (Max * sizeof(int));
printf("Please int %d numbers\n",l.length);
for (int i = 0; i < l.length ; i ++)
scanf("%d",&l.data[i]);
}//建立一个顺序表,通过顺序表给哈希表赋值

void InitHashSqlist(Sqlist l,HashSqlist &hl){
hl.data = (int *)malloc (Max * sizeof (int ));
hl.length = Size;
int i,j,key;
for (i = 0; i < hl.length; i ++)
hl.data[i] = 0;
for (i = 0; i < l.length ; i ++){
key = hash(l.data[i]);
if (hl.data [key]  != NULL){
for (j = 1;  hl.data[key] != NULL; j ++)
key = hash(l.data[i] + j);
}
hl.data[key] = l.data[i] ;
printf("%d ----%d \n",key,hl.data[key]);//顺便输出,方便检验
}
}

void OutPut(HashSqlist hl){
	int key ;
	for (key = 0; key < hl.length; key ++){
	if (hl.data[key]  == 0){
		key = key;
	}
	else
	printf("%d----%d \n",key , hl.data[key]);
}
}//哈希表输出

void Find(HashSqlist hl){
	int address;
	printf("please int an address to find !\n");
	scanf("%d",&address);
	printf("The number is : %d\n",hl.data[address]);
}//根据地址查找

void Delete(HashSqlist hl){
	int address;
	printf("please int the address of the element that you want to delete!\n");
	scanf("%d",&address);
	hl.data[address] = 0;
	printf ("Now, the HashSqlist is :\n");
	OutPut(hl);
}//删除地址元素

void Insert(HashSqlist hl){
	int i;
	printf("Please int the number that you want to insert!\n");
	scanf("%d",&i);
	int key = i;
	if (hl.data [key]  != NULL){
    for (int j = 1;  hl.data[key] != NULL; j ++)
    key = hash(hl.data[key] + j);
	}
	hl.data[key] = i;
	OutPut(hl);
}//插入元素

int main (){
Sqlist l;
HashSqlist hl;
InitSqlist(l);
InitHashSqlist(l,hl);
Find(hl);
Delete(hl);
Insert(hl);
return 0;
}


	

实例

标签:hl,int,哈希,插入,length,查找,key,printf,data
来源: https://blog.csdn.net/hzhzhu/article/details/112352070