哈希表代码实现

main.c

#include "hash.h"
int main(int argc, const char *argv[])
{	
	H_P R=create_row();
	int num_1;
	scanf("%d",&num_1);
	for(int i=0;i<num_1;++i)
	{
		int num_2;
		scanf("%d",&num_2);
		int pos_1=num_2%NUM;
		insert_pos(R,pos_1,num_2);
	}
	int ret_1=hash_seek(R,2,1);
	printf("目标值为%d\n",ret_1);
	printf("当前哈希表存储数据为:\n");
	show_hash(R,num_1);
	return 0;
}

hash.c

#include "hash.h"
//1、申请哈希表
H_P create_row()
{
	H_P R=(H_P)malloc(sizeof(hash_list));
	if(R==NULL)
	{
		printf("申请空间失败");
		return NULL;
	}
	for(int i=0;i<MAX;i++)
	{
		R->row[i]=NULL;
	}
	return R;
}
//2、创建结点
N_P create_line(int value)
{
	N_P new=(N_P)malloc(sizeof(node));
	if(new==NULL)
	{
		printf("申请空间失败\n");
		return NULL;
	}
	new->data=value;
	new->next=NULL;
	return new;
}
//3、插入结点
void insert_pos(H_P R , int pos , int value)
{
	if(R==NULL) {return ;}
	int i;
	for(i=0;i<=pos-1;++i);
	N_P new=create_line(value);
	if(R->row[i]==NULL)
	{
	R->row[i]=(H_P)new;
	return ;
	}
	else
	{
		new->next=(N_P)R->row[i];
		R->row[i]=(H_P)new;
	}
	return ;
}
//4、从哈希表查找数据
int hash_seek(H_P R , int pos1 , int pos2)
{
	if(R==NULL)  {return -1;}
	if(pos1<0 || pos1>MAX-1 || pos2<0)
	{
		printf("查找位置不合理\n");
		{return -2;}
	}
	int i,j=0,ret;
	for(i=0;i<pos1-1;++i);
	H_P p=R->row[i];
	N_P q=(N_P)p;
	while(j<pos2-1)
	{
		if(q==NULL) 
		{
			printf("查找位置超出哈希表范围\n");
			return -3;
		}
		q=q->next;
		j++;
	}
	ret=q->data;
	return ret;
}
//5、输出哈希表
void show_hash(H_P R)
{
	if(R==NULL) {return ;}
		H_P p;
		N_P q;
	for(int i=0;i<MAX;++i)
	{
		p=R->row[i];
		q=(N_P)p;
		while(q!=NULL)
		{
			printf("%d->",q->data);
			q=q->next;
		}
			printf("\n");
	}
	return;
}

hash.h

#ifndef __HASH_H__
#define __HASH_H__
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NUM 26
#define MAX NUM*4/3
typedef struct node
{
	int data;
	struct node* next;
}node , * N_P;
typedef struct hash_list
{
	struct hash_list *row[MAX];
}hash_list , * H_P;
H_P create_row();
N_P create_line(int value);
void insert_pos(H_P R , int pos , int value);
int hash_seek(H_P R , int pos1 , int pos2);
void show_hash(H_P R); 
#endif

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值