Struktur Data -> Hashing and Chaining
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 5
typedef struct element
{
char data[100];
struct element * next;
}element;
element * chain[max];
void init()
{
int i;
for(i=0;i<max;i++)
{
chain[i] = NULL;
}
}
void insert(char data[100])
{
element * bantu;
bantu = (element*)malloc(sizeof(element));
strcpy(bantu->data,data);
bantu->next = NULL;
int i,nilai;
nilai = 0;
for(i=0;i<strlen(data);i++)
{
nilai = nilai + (int) data[i];
}
int key;
key = nilai % max;
if(chain[key] == NULL)
{
chain[key] = bantu;
}else
{
element * membantu;
membantu = chain[key];
while(membantu == NULL)
{
membantu = membantu->next;
}
membantu->next = bantu;
}
}
void print()
{
int i;
for(i=0;i<max;i++)
{
printf("chain[%d]->",i);
while(chain[i] != NULL)
{
printf("%s->",chain[i]->data);
chain[i] = chain[i]->next;
}
printf("NULL \n");
}
}
int main()
{
init();
char masukan[100];
scanf("%s",masukan);
insert(masukan);
print();
return 0;
}
Komentar
Posting Komentar