hash_table.c 函数的定义
#include"hash_table.h"
int creat_table(hash_table_t **hash_table){
if(NULL==hash_table){
printf("入参为空,请检查..\n");
return -1;
}
*hash_table=(hash_table_t *)malloc(sizeof(hash_table_t));
if(NULL==*hash_table){
printf("分配空间失败,请检查..\n");
return -1;
}
(*hash_table)->size=table_len;
int i=0;
for(i=0;i<table_len;i++){
(*hash_table)->table[i]=NULL;
}
return 0;
}
int add_student(student_t **student,int id,char *name){
if(NULL==student){
printf("入参为空,请检查..\n");
return -1;
}
*student=(student_t *)malloc(sizeof(student_t));
if(NULL==*student){
printf("分配空间失败,请检查..\n");
return -1;
}
(*student)->number=id;
strcpy((*student)->name,name);
return 0;
}
int insert_student(hash_table_t *hash_table, student_t *student){
if(NULL==student||NULL==hash_table){
printf("入参为空,请检查..\n");
return -1;
}
node_t *node=(node_t *)malloc(sizeof(node_t));
if(NULL==node){
printf("分配空间失败,请检查..\n");
return -1;
}
node->data=student;
node->next=NULL;
int s=node->data->name[0]-'a';
if(NULL==hash_table->table[s]){
hash_table->table[s]=(int *)node;
}else{
node_t *temp=(node_t *)hash_table->table[s];
while(NULL!=temp->next){
temp=temp->next;
}
temp->next=node;
}
}
int search_table(hash_table_t *hash_table,char c){
if(NULL==hash_table){
printf("入参为空,请检查..\n");
return -1;
}
int b=c;
int s=b-'a';
node_t *temp=(node_t *)hash_table->table[s];
while(temp){
if(temp->data->name[0]==c){
printf("%d,%s\n",temp->data->number,temp->data->name);
}
temp=temp->next;
}
return 0;
}
hash_table.h 函数的声明、结构体定义、头文件
#ifndef __HASH_H__
#define __HASH_H__
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define table_len 26
typedef struct STUDENT{
int number;
char name[32];
}student_t;
typedef struct NODE_t{
student_t *data;
struct NODE_t *next;
}node_t;
typedef struct HASH_table{
int size;
int *table[table_len];
}hash_table_t;
int creat_table(hash_table_t **hash_table);
int add_student(student_t **student,int id,char *name);
int insert_student(hash_table_t *hash_table,student_t *student);
int search_table(hash_table_t *hash_table,char c);
#endif
hash_main.c 函数入口
#include"hash_table.h"
int main(){
hash_table_t *hash_table=NULL;
creat_table(&hash_table);
//printf("%p\n",hash_table);
student_t *student=NULL;
add_student(&student,2019,"yu");
//add_student(&student,2019,"yy");
// printf("%d,%s\n",student->number,student->name);
insert_student(hash_table,student);
add_student(&student,2000,"yx");
insert_student(hash_table,student);
// insert_student(hash_table,student);
search_table(hash_table,'y');
return 0;
}