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
运行结果

793

被折叠的 条评论
为什么被折叠?



