This repository has been archived on 2019-08-08. You can view files and clone it, but cannot push or open issues or pull requests.
s6-pa-tp/TP5/questions.c
Geoffrey Frogeye 46b1ecc22c TP5 + 1/2 questions supplémentaires
Intersection ne fonctionne pas encore
2017-03-15 12:10:20 +01:00

129 lines
2.2 KiB
C
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include<stdlib.h>
#include<stdio.h>
#include<stdbool.h>
// 2.2.1
struct Cellule {
struct Cellule* suiv;
int val;
int mult;
};
typedef struct Cellule Cellule;
void ajout_tete(Cellule** l, int val, int mult) {
Cellule* p;
p = malloc(sizeof(Cellule));
p->val = val;
p->suiv = *l;
p->mult = mult;
*l = p;
}
void imprimer(Cellule* l) {
while (l != NULL) {
printf("%d × %d\n", l->val, l->mult);
l = l->suiv;
}
}
void supprimer_tete(Cellule** l) {
Cellule* p;
p = (*l)->suiv;
free(*l);
*l = p;
}
// 2.2.2
void inserer(Cellule** p, int val) {
Cellule* l = *p;
if (l == NULL) {
ajout_tete(p, val, 1);
} else if (l->val == val) {
l->mult++;
} else if (l->val > val) {
ajout_tete(p, val, 1);
} else {
inserer(&l->suiv, val);
}
}
// 2.2.3
Cellule* lire_fichier(FILE* fp) {
Cellule* l = NULL;
int val;
while (fscanf(fp, "%d", &val) != EOF) {
inserer(&l, val);
}
return l;
}
// 2.3.1
bool est_trie(Cellule* l) {
if (l == NULL || l->suiv == NULL) {
return true;
}
if (l->val < l->suiv->val) {
return est_trie(l->suiv);
} else {
return false;
}
}
// 2.3.2
void desallouer(Cellule* l) {
if (l == NULL) {
return;
}
desallouer(l->suiv);
free(l);
}
// 2.3.3
int multiplicite(Cellule* l, int val) {
if (l == NULL) {
return 0;
}
if (l->val == val) {
return l->mult;
} else {
return multiplicite(l->suiv, val);
}
}
// 2.3.3
int cardinal(Cellule* l) {
if (l == NULL) {
return 0;
}
return l->mult + cardinal(l->suiv);
}
int main(int argc, char* argv[]) {
if (argc != 2) {
printf("Usage : %s FICHIER_ENTREE\n", argv[0]);
return EXIT_FAILURE;
}
FILE* fp;
fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Impossible d'ouvrir le fichier %s.\n", argv[1]);
return EXIT_FAILURE;
}
Cellule* l = lire_fichier(fp);
fclose(fp);
imprimer(l);
printf("l est trié : %d\n", est_trie(l));
printf("multiplicité de 3 : %d\n", multiplicite(l, 3));
printf("cardinal de l : %d\n", cardinal(l));
desallouer(l);
}