home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
ftp.disi.unige.it
/
2015-02-11.ftp.disi.unige.it.tar
/
ftp.disi.unige.it
/
pub
/
.person
/
CataniaB
/
teach-act
/
testi-esami
/
labo-10.00
/
parte2.c
< prev
next >
Wrap
C/C++ Source or Header
|
2001-01-14
|
2KB
|
143 lines
#include<stdio.h>
#include<stdlib.h>
#define B 10
/* la soluzione propone allocazione dinamica della tabella hash */
/* gli esercizi potevano essere risolti anche con allocazione
statica */
typedef struct cell{int el;
struct cell*next;} cell;
typedef cell*list; typedef list*hash;
int h(int);
hash empty();
void insert(int,hash);
void delete(int,hash);
void print(hash);
int h(int n)
{return(n%B);}
hash empty() {
hash t;
int i;
t=(hash)calloc(B,sizeof(list));
for(i=0;i<B;i++)
t[i]=NULL;
return t;
}
void insert(int n,hash t) {
int b=h(n);
list l=t[b];
list prec=NULL, aux;
// scandisco la lista per trovare la posizione in cui inserire la nuova cella
while (l!=NULL && l->el<n)
{
prec=l;
l=l->next;
}
if (prec == NULL && (l == NULL || l ->el !=n)) // inserimento in testa
{
aux=(list)malloc(sizeof(cell));
aux->el=n;
aux->next=t[b];
t[b]=aux;
return;
}
if (l == NULL) // inserimento in fondo
{
aux=(list)malloc(sizeof(cell));
aux->el=n;
prec ->next = aux;
aux ->next = NULL;
return;
}
/* se le prime due condizioni non sono verificate, l'inserimento
deve essere effettuato nel mezzo della lista */
if (l->el !=n) /* l'elemento non e` gia` presente */
{
aux=(list)malloc(sizeof(cell));
aux->el=n;
prec ->next = aux;
aux ->next = l;
}
}
void delete(int n,hash t)
{
list l=t[h(n)];
list prec=NULL;
while((l!=NULL) && (l->el<n))
{prec=l; l=l->next;}
if (l!=NULL && l->el==n)
{
if(prec==NULL)
t[h(n)]=l->next;
else
prec->next=l->next;
free(l);
}
}
void print(hash t) {
int i;
list l;
for (i=0;i<B;i++)
{
printf("\n%d: ",i);
for(l=t[i];l!=NULL;l=l->next)
printf("%d ",l->el);
printf("\n");
}
}
main() {
char nome[20];
int n;
hash t;
FILE*fp;
t=empty();
printf("\nFornisci nome del file: ");
scanf("%s",nome);
if(fp=fopen(nome,"r"))
{
while(fscanf(fp,"%d",&n) && n!=-1)
insert(n,t);
}
else exit(EXIT_FAILURE);
printf("\n\nLa tabella e':\n");
print(t);
printf("\n\nFornisci numero da cancellare: \n");
scanf("%d",&n);
delete(n,t);
printf("\n\nLa nuova tabella e': \n");
print(t);
fclose(fp);
return 0;
}