Add latest implementation of tree algorithm in TP6 directory
[Algorithmic_C.git] / TP6 / hachage / chainage / hachage_chainage.c
CommitLineData
249ff697
JB
1/******************************************************************************/
2/* Hachage par chainage */
3/******************************************************************************/
4#include <stdlib.h>
5#include <stdio.h>
6
7#define M 5
8/* on choisit M tres petit pour tester le programme, mais en realite,
9 M est tres grand */
10
11typedef int element;
12
13typedef struct cellule {element valeur;
14 struct cellule *suivant; } Cellule, *Liste;
15
16typedef struct {Liste T[M]; } t_table;
17
18int h(element x) {return x%M; }
19/* "mauvaise" fonction de hachage - juste pour tester le programme */
20
21t_table init_table()
22 {t_table t;
23 int i;
24 for (i=0; i<M; i++) t.T[i]=NULL;
25 return t;}
26
27
28int rechercher(element x, t_table t)
29 {int i=h(x);
30 Cellule *p=t.T[i];
31 while (p) if (x==p->valeur) return 1;
32 else p=p->suivant;
33 return 0;
34 }
35
36int inserer(element x, t_table *t)
37/* retourne 0 si x est deja dans la table */
38 {int i=h(x);
39 Cellule *p=t->T[i], *preced=NULL;
40 while (p) if (x==p->valeur) return 0;
41 else {preced = p; p=p->suivant; }
42 if (preced==NULL) {t->T[i]=(Cellule *)malloc(sizeof(Cellule));
43 t->T[i]->valeur=x;
44 t->T[i]->suivant=NULL;
45 }
46 else {preced->suivant=(Cellule *)malloc(sizeof(Cellule));
47 preced->suivant->valeur=x;
48 preced->suivant->suivant=NULL;
49 }
50 return 1;
51 }
52
53void visu(Liste L)
54 {if (L){printf("%d\t",L->valeur);
55 visu(L->suivant);
56 }
57 }
58
59void afficher(t_table t)
60 {Cellule *p;
61 int i;
62 for (i=0; i<M ; i++)
63 if (t.T[i]) {printf("t[%d]=\t",i); visu(t.T[i]); printf("\n");}
64 printf("\n");
65 }
66
67/******************************************************************************/
68int main ()
69{t_table t;
70
71t=init_table();
72afficher(t);
73inserer(3,&t); afficher(t);
74printf("%d\n",rechercher(3,t));
75printf("%d\n",rechercher(12,t));
76inserer(5,&t); afficher(t);
77inserer(13,&t); afficher(t);
78inserer(9,&t); afficher(t);
79inserer(19,&t); afficher(t);
80inserer(23,&t); afficher(t);
81}
82/*****************************************************************************
83Etat de la table a la fin du programme
84--------------------------------------
85t[0]= 5
86t[3]= 3 13 23
87t[4]= 9 19
88*****************************************************************************/