Hashテーブルの挿入、削除、検索
2803 ワード
#include "stdio.h"
#include "stdlib.h"
#include "memory.h"
struct hashNode
{
int data;
hashNode *next;
};
struct hashTable
{
hashNode *value[10];
};
// hash ( )
hashTable * createHashtable()
{
hashTable *phashTb1=(hashTable*)malloc(sizeof(hashTable));
memset(phashTb1,0,sizeof(hashTable));
return phashTb1;
}
// hash
hashNode *findInHashTable(hashTable *phashtb1,int data)
{
hashNode *pNode;
if(NULL==phashtb1)
return NULL;
if(NULL==(pNode=phashtb1->value[data%10]))
return NULL;
while(pNode)
{
if(pNode->data==data)
return pNode;
else
{
pNode=pNode->next;
}
}
return NULL;
}
// hash
bool insertDataInHashTable(hashTable *phashtb1,int data)
{
hashNode *pNode;
if(NULL == phashtb1)
return false;
if(NULL==phashtb1->value[data%10])
{
pNode=(hashNode*)malloc(sizeof(hashNode));
memset(pNode,0,sizeof(hashNode));
pNode->data=data;
phashtb1->value[data%10]=pNode;
return true;
}
/*
if(NULL==findInHashTable(phashtb1,data))
return false;
*/
pNode=phashtb1->value[data%10];
while(pNode->next)
pNode=pNode->next;
pNode->next=(hashNode*)malloc(sizeof(hashNode));
memset(pNode->next,0,sizeof(pNode));
pNode->next->data=data;
pNode->next->next=NULL;
return true;
}
// hash
bool delete_data_from_hash(hashTable* pHashtb1,int data)
{
hashNode *pNode;
if(NULL==pHashtb1||NULL==pHashtb1->value[data%10])
return false;
if(NULL==findInHashTable(pHashtb1,data))
return false;
if(data==pHashtb1->value[data%10]->data)
{
pNode=pHashtb1->value[data%10];
pHashtb1->value[data%10]=pHashtb1->value[data%10]->next;
free(pNode);
return true;
}
pNode=pHashtb1->value[data%10];
hashNode *pHead=pNode;
pNode=pNode->next;
while(pNode->data!=data)
{
pNode=pNode->next;
pHead=pHead->next;
}
pHead->next=pNode->next;
pNode->next=NULL;
free(pNode);
}
int main()
{
hashTable *pHashTbl=createHashtable();
insertDataInHashTable(pHashTbl,1);
insertDataInHashTable(pHashTbl,2);
insertDataInHashTable(pHashTbl,3);
insertDataInHashTable(pHashTbl,4);
insertDataInHashTable(pHashTbl,5);
insertDataInHashTable(pHashTbl,6);
insertDataInHashTable(pHashTbl,7);
insertDataInHashTable(pHashTbl,8);
insertDataInHashTable(pHashTbl,9);
insertDataInHashTable(pHashTbl,10);
insertDataInHashTable(pHashTbl,11);
insertDataInHashTable(pHashTbl,12);
insertDataInHashTable(pHashTbl,13);
insertDataInHashTable(pHashTbl,14);
insertDataInHashTable(pHashTbl,15);
insertDataInHashTable(pHashTbl,16);
insertDataInHashTable(pHashTbl,17);
insertDataInHashTable(pHashTbl,18);
delete_data_from_hash(pHashTbl,3);
delete_data_from_hash(pHashTbl,13);
return 0;
}