Piles & files
vendredi 25 juillet 2025
en cours de rédaction
?
1 – Piles de nombres entiers
?
#include <stdio.h>
#include <stdlib.h>
struct _pile
{
int Sommet ;
struct _pile *Dessous ;
} ;
typedef struct _pile pile ;
void Empiler(int x, pile **PL)
{
pile *NouvellePL = malloc(sizeof(pile)) ;
NouvellePL->Sommet = x ;
NouvellePL->Dessous = *PL ;
*PL = NouvellePL ;
}
int Depiler(pile **PL)
{
int x = (*PL)->Sommet ;
pile NouvellePL = (*PL)->Dessous ;
free(*PL) ;
*PL = NouvellePL ;
return x ;
}
int main()
{
pile *PL = NULL ;
int i ;
/* Empilages */
for(i = 1 ; i <= 5 ; i++)
{
Empiler(i, &PL) ;
}
/* Dépilages */
while(PL != NULL)
{
printf("%d\n", Depiler(&PL)) ;
}
return 0 ;
}
5
4
3
2
1
2 – Piles d'objets quelconques
?
struct _pile
{
void *Sommet ;
struct _pile *Dessous ;
} ;
typedef struct _pile pile ;
void Empiler(void *x, pile **PL)
{
pile *NouvellePL = malloc(sizeof(pile)) ;
NouvellePL->Sommet = x ;
NouvellePL->Dessous = *PL ;
*PL = NouvellePL ;
}
void *Depiler(pile **PL)
{
void *x = (*PL)->Sommet ;
pile *NouvellePL = (*PL)->Dessous ;
free(*PL) ;
*PL = NouvellePL ;
return x ;
}
int main()
{
pile *PL = NULL ;
int i ;
int *x = NULL ;
/* Empilages */
for(i = 1 ; i <= 5 ; i++)
{
x = malloc(sizeof(int)) ;
*x = i ;
Empiler(x, &PL) ;
}
/* Dépilages */
while(PL != NULL)
{
x = Depiler(&PL) ;
printf("%d\n", *x) ;
free(x) ;
}
return 0 ;
}
5
4
3
2
1
3 – Files non bornées
?
struct _file
{
pile *Entrants ;
pile *Sortants ;
} ;
typedef struct _file file ;
void Enfiler(void *x, file *FL)
{
Empiler(x, &(FL->Entrants)) ;
}
void Transvaser(file *FL)
{
while(FL->Entrants != NULL)
{
Empiler(Depiler(&(FL->Entrants)), &(FL->Sortants)) ;
}
}
void *Defiler(file *FL)
{
if(FL->Sortants == NULL) {Transvaser(FL) ;}
return Depiler(&(FL->Sortants)) ;
}
#define VRAI 1
#define FAUX 0
typedef int bool ;
bool EstNonVide(file *FL)
{
return (FL->Entrants != NULL) || (FL->Sortants != NULL) ;
}
file *CreerFile()
{
file *FL = malloc(sizeof(file)) ;
FL->Entrants = NULL ;
FL->Sortants = NULL ;
return FL ;
}
void DetruireFile(file *FL)
{
/* S'il y a des éléments, on les retire. */
while(EstNonVide(FL)) {Defiler(FL) ;}
free(FL) ;
}
int main()
{
file *FL = CreerFile() ;
int i ;
int *x = NULL ;
/* Enfilages */
for(i = 1 ; i <= 5 ; i++)
{
x = malloc(sizeof(int)) ;
*x = i ;
Enfiler(x, FL) ;
}
/* Défilages */
while(EstNonVide(FL))
{
x = Defiler(FL) ;
printf("%d\n", *x) ;
free(x) ;
}
DetruireFile(FL) ;
return 0 ;
}
1
2
3
4
5