[c언어 자료구조] 해싱
율하
#include stdio.h
#include stdlib.h
#include memory.h
#define BK 5
struct node
{
int data;
struct node *link;
};
struct node *hashtable[BK];
int hash(int key)
{
return key % BK;
}
void AddKey(int key)
{
int bucket = hash(key);
struct node *search;
struct node *tmp = (struct node *)malloc(sizeof(struct node));
tmp-data = key;
tmp-link = NULL;
printf(AddKey : %d %d\n, bucket, key);
if(hashtable[bucket] == NULL)
hashtable[bucket] = tmp;
else
{
search = hashtable[bucket];
while(1)
{
if(search-link == NULL)
{
search-link = tmp;
break;
}
search = search-link;
}
}
}
void Delete(struct node *tmp)
{
struct node *dump;
printf(\nDelete\n);
while(tmp)
{
printf(%3d , tmp-data);
dump = tmp;
tmp = dump-link;
free(dump);
}
}
int FindKey(int key)
{
int bucket = hash(key);
struct node *tmp = hashtable[bucket];
while(1)
{
if(tmp-data == key)
{
printf([%d] : %d 찾음!!\n, bucket, tmp-data);
return 1;
}
tmp = tmp-link;
return 0;
}
}
int main()
{
int i;
memset(hashtable, NULL, sizeof(hashtable));
AddKey(45);
AddKey(15);
AddKey(21);
AddKey(7);
printf(Search key : );
scanf(%d, &i);
if(FindKey(i))
printf(검색성공!\n);
else
printf(찾을수 없음!\n);
for(i=0;iBK;i++)
Delete(hashtable[i]);
return 0;
}
// Search key에서 15를 입력하면 찾을 수 없음 으로 나와요ㅜ.ㅜ
// 어떤 부분이 잘못 된걸까요??