Main.c
#include <stdio.h>
#include <stdlib.h>
#include "HT.h"
int main()
{
int i;
char *str="ab", *str2 = "ba";
link head;
head = HTinit();
HTagg(head, str);
if(cercaRI(head, str2)) printf("Trovata");
else printf("non trovata");
HTfreeR(head);
free(head);
return 0;
}
HT.h
#include <string.h>
/*#define Item int
#define eq(A, B) A==B
#define NULLitem -1*/
#define Item char
#define eq(A, B) strcmp(A, B)==0
#define NULLitem 0
typedef struct nodo *link;
struct nodo
{
Item item;
link *next;
};
int HASH(Item c);
link HTinit();
void HTagg(link testa, Item *key);
int cercaRI(link t, Item *key);
void HTfreeR(link t);
HT.c
#include "HT.h"
#define M 27
int HASH(Item c)
{
int h, base = 11;
h = (base + c)%M;
return h;
}
link HTinit()
{
int i;
link testa = malloc(sizeof(link));
testa->item = NULLitem;
testa->next = malloc(M*sizeof(link *));
for(i=0; i<M; i++) testa->next[i] = NULL;
return testa;
}
void HTagg(link testa, Item *key)
{
int h, i;
link x;
link t = testa;
/*cnverti tutto in minuscolo*/
for(; (*key)!='\0'; key++)
{
h = HASH(*key);
if(t->next[h]==NULL)
{
x=malloc(sizeof(link));
x->item = (*key);
x->next = malloc(M*sizeof(link *));
for(i=0; i<M; i++) x->next[i] = NULL;;
t->next[h] = x;
}
t=t->next[h];
}
return;
}
int cercaRI(link t, Item *key)
{
if((*key)=='\0') return 1;
int h = HASH(*key);
if(t->next[h]!=NULL)
if(cercaRI(t->next[h], ++key)) return 1;
return 0;
}
void HTfreeR(link t)
{
int i;
for(i=0; i<M; i++)
{
if(t->next[i]!=NULL)
HTfreeR(t->next[i]);
}
free(t->next);
free(t);
return;
}
Io credo che deallochi più del dovuto.