Ajout des TP
This commit is contained in:
98
BUT1/CONTROLE/CM3/exo3/exo3.c
Normal file
98
BUT1/CONTROLE/CM3/exo3/exo3.c
Normal file
@@ -0,0 +1,98 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Structure pour un nœud dans la liste chaînée*/
|
||||
typedef struct Noeud {
|
||||
int digit;
|
||||
struct Noeud* suivant;
|
||||
} Noeud;
|
||||
|
||||
/* Fonction pour convertir une représentation décimale en liste chaînée*/
|
||||
Noeud* convertirListeChainee(char* nombre) {
|
||||
Noeud* liste = NULL;
|
||||
int i;
|
||||
int length = strlen(nombre);
|
||||
|
||||
for (i = length - 1; i >= 0; i--) {
|
||||
Noeud* nouveauNoeud = (Noeud*)malloc(sizeof(Noeud));
|
||||
nouveauNoeud->digit = nombre[i] - '0';
|
||||
nouveauNoeud->suivant = liste;
|
||||
liste = nouveauNoeud;
|
||||
}
|
||||
|
||||
return liste;
|
||||
}
|
||||
|
||||
/* Fonction pour afficher une liste chaînée*/
|
||||
void AfficherListe(Noeud* liste) {
|
||||
while (liste != NULL) {
|
||||
printf("%d", liste->digit);
|
||||
liste = liste->suivant;
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
/* Fonction pour additionner deux listes chaînées*/
|
||||
Noeud* ajouterAListe(Noeud* num1, Noeud* num2) {
|
||||
Noeud* resultat = NULL;
|
||||
Noeud* actuel = NULL;
|
||||
Noeud* nouveauNoeud = NULL;
|
||||
int retenue = 0;
|
||||
int somme;
|
||||
|
||||
while (num1 != NULL || num2 != NULL || retenue != 0) {
|
||||
somme = retenue;
|
||||
|
||||
if (num1 != NULL) {
|
||||
somme += num1->digit;
|
||||
num1 = num1->suivant;
|
||||
}
|
||||
|
||||
if (num2 != NULL) {
|
||||
somme += num2->digit;
|
||||
num2 = num2->suivant;
|
||||
}
|
||||
|
||||
nouveauNoeud = (Noeud*)malloc(sizeof(Noeud));
|
||||
nouveauNoeud->digit = somme % 10;
|
||||
nouveauNoeud->suivant = NULL;
|
||||
|
||||
retenue = somme / 10;
|
||||
|
||||
if (resultat == NULL) {
|
||||
resultat = nouveauNoeud;
|
||||
actuel = resultat;
|
||||
} else {
|
||||
actuel->suivant = nouveauNoeud;
|
||||
actuel = nouveauNoeud;
|
||||
}
|
||||
}
|
||||
|
||||
return resultat;
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
Noeud* num1 = NULL;
|
||||
Noeud* num2 = NULL;
|
||||
Noeud* somme = NULL;
|
||||
char* nombre1;
|
||||
char* nombre2;
|
||||
if (argc != 3) {
|
||||
perror("Usage: %s <nombre1> <nombre2>\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
nombre1 = argv[1];
|
||||
nombre2 = argv[2];
|
||||
|
||||
|
||||
num1 = convertirListeChainee(nombre1);
|
||||
num2 = convertirListeChainee(nombre2);
|
||||
somme = ajouterAListe(num1, num2);
|
||||
|
||||
|
||||
AfficherListe(somme);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
Reference in New Issue
Block a user