哈希表结构:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ok 1
#define fail 0
typedef struct Tnode
{
int data;
struct Tnode *next;
} Node;
typedef struct _Hash_Table
{
Node* value[10];
} Hash_Table;
Hash_Table* create_hash_table(void)
{
Hash_Table* hashpoint=(Hash_Table*)malloc(sizeof(Hash_Table));
int i=0;
for(i=0;i<10;i++)
{
hashpoint->value[i]=NULL;
}
if(hashpoint==NULL)
printf("Create the hash table error~\n");
return hashpoint;
}
Node* find_data_in_hash(Hash_Table *hashpoint ,int data)
{
Node *node_find;
Node *hash_node;
hash_node=hashpoint->value[data%10];
if(hash_node==NULL)
return NULL;
if(hash_node->data==data)
return hash_node;
node_find=hash_node->next;
while(node_find!=NULL)
{
if(node_find->data==data)
return node_find;
else
node_find=node_find->next;
}
return NULL;
}
int insert_data_to_hash(Hash_Table *hashpoint,int data)
{
Node *node_insert;
Node *hash_node=hashpoint->value[data%10];
if(hash_node==NULL)
{
node_insert=(Node*)malloc(sizeof(struct Tnode));
if(node_insert==NULL)
{
printf("malloc failed!\n");
return fail;
}
hash_node=node_insert;
node_insert->data=data;
node_insert->next=NULL;
hashpoint->value[data%10]=node_insert;
printf("Insert the data OK!\n");
return ok;
}
if(find_data_in_hash(hashpoint,data))
{
printf("This data existed alreadly.\n");
return fail;
}
node_insert=hash_node;
while(node_insert->next!=NULL)
{
node_insert=node_insert->next;
}
node_insert->next=(Node*)malloc(sizeof(Node));
if(node_insert->next==NULL)
{
printf("Failed to malloc!\n");
return fail;
}
node_insert->next->data=data;
node_insert->next->next=NULL;
printf("Insert the data OK!\n");
return ok;
}
Node* del_data(Hash_Table *hashpoint,int data)
{
Node *node_del=hashpoint->value[data%10];
if(node_del==NULL&&hashpoint!=NULL)
{
printf("Doesn't exist this data.\n");
return NULL;
}
Node* pnode;
pnode=find_data_in_hash(hashpoint,data);
if(pnode==NULL)
{
printf("Doesn't exist this data.\n");
return NULL;
}
if(pnode==node_del)
{
hashpoint->value[data%10]=pnode->next;
pnode->next=NULL;
free(pnode);
printf("Delect the data OK1!\n");
return NULL;
}
while(node_del->next!=pnode)
node_del=node_del->next;
node_del->next=pnode->next;
pnode->next=NULL;
free(pnode);
printf("Delect the data OK2!\n");
return NULL;
}
int print_hash_data(Hash_Table *hashpoint)
{
int i=0;
for(i=0;i<10;i++)
{
Node* printpoint=hashpoint->value[i];
while(printpoint!=NULL)
{
printf("The table[%d] is %d\n",i,printpoint->data);
printpoint=printpoint->next;
}
}
return ok;
}
int main()
{
Hash_Table *hash_table=create_hash_table();
int i=0;
while(i<15)
{
int data;
printf("Input the %d number you wanted to insert:",i);
scanf("%d",&data);
if(insert_data_to_hash(hash_table,data))
i++;
}
print_hash_data(hash_table);
del_data(hash_table,3);
print_hash_data(hash_table);
del_data(hash_table,33);
print_hash_data(hash_table);
}