#include "hash.h" #include #include #include int hash_f( char *s ) { int tmp; int i; tmp = 0; for( i = 0; i < strlen( s ); i++ ) tmp += (int)s[i]; tmp = tmp % HASH_TABLE_SIZE; return( tmp ); } void create( TABLE_EL **t ) { int i; TABLE_EL *ptr; ptr = (TABLE_EL *)malloc( sizeof( TABLE_EL )*HASH_TABLE_SIZE ); if( ptr == NULL ) { printf( "Impossibile allocare la memoria\n" ); exit( 1 ); } for( i = 0; i < HASH_TABLE_SIZE; i++ ) { ptr[i].word = NULL; ptr[i].freq = 0; } *t = ptr; } void insert( TABLE_EL *t, TABLE_EL *e ) { int i; int tmp; tmp = hash_f( e->word ); if( t[tmp].word == NULL ) { /* Inserimento senza collisione */ t[tmp].word = (char *)strdup( e->word ); t[tmp].freq = e->freq; return; } else { for( i = tmp+1; i < HASH_TABLE_SIZE; i++ ) if( t[i].word == NULL ) { t[i].word = (char *)strdup( e->word ); t[i].freq = e->freq; return; } printf( "Impossible aggiungere il nuovo elemento\n" ); exit( 1 ); } } TABLE_EL *search( TABLE_EL *t, char *s ) { /* Open addressing */ int i; int tmp; tmp = hash_f( s ); if( t[tmp].word == NULL ) return( NULL ); /* L'elemento non esiste */ if( !strcmp( t[tmp].word, s ) ) return( &(t[tmp]) ); /* Trovato */ else { /* Si e` verificata una collisione */ for( i = tmp+1; i < HASH_TABLE_SIZE; i++ ) { if( t[i].word == NULL ) return( NULL ); /* L'elemento non esiste */ if( !strcmp( t[i].word, s ) ) return( &(t[i]) ); /* Trovato */ } return( NULL ); /* L'elemento non esiste */ } } void dispose( TABLE_EL **t ) { int i; TABLE_EL *ptr; ptr = *t; for( i = 0; i < HASH_TABLE_SIZE; i++ ) if( ptr[i].word != NULL ) free( ptr[i].word ); free( *t ); *t = NULL; }