90 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			C
		
	
	
	
	
	
			
		
		
	
	
			90 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			C
		
	
	
	
	
	
| #include <stdio.h>
 | |
| #include <stdlib.h>
 | |
| #include <string.h>
 | |
| 
 | |
| /* Structure d'un nœud de la liste chaînée */
 | |
| typedef struct Node {
 | |
|     int digit;
 | |
|     struct Node *next;
 | |
| } Node;
 | |
| 
 | |
| /* Fonction pour ajouter un chiffre à la fin de la liste chaînée */
 | |
| Node* ajouter_chiffre(Node *head, int digit) {
 | |
|     Node *new_node = (Node*)malloc(sizeof(Node));
 | |
|     if (new_node == NULL) {
 | |
|         fprintf(stderr, "Erreur d'allocation memoire\n");
 | |
|         exit(EXIT_FAILURE);
 | |
|     }
 | |
|     new_node->digit = digit;
 | |
|     new_node->next = NULL;
 | |
|     if (head == NULL) {
 | |
|         return new_node;
 | |
|     }
 | |
|     Node *temp = head;
 | |
|     while (temp->next != NULL) {
 | |
|         temp = temp->next;
 | |
|     }
 | |
|     temp->next = new_node;
 | |
|     return head;
 | |
| }
 | |
| 
 | |
| /* Fonction pour convertir une chaîne en liste chaînée */
 | |
| Node* convertir_en_liste(const char *nombre) {
 | |
|     Node *head = NULL;
 | |
|     int i;
 | |
|     for (i = 0; nombre[i] != '\0'; i++) {
 | |
|         head = ajouter_chiffre(head, nombre[i] - '0');
 | |
|     }
 | |
|     return head;
 | |
| }
 | |
| 
 | |
| /* Fonction pour afficher la liste chaînée */
 | |
| void afficher_liste(Node *head) {
 | |
|     while (head != NULL) {
 | |
|         printf("%d", head->digit);
 | |
|         head = head->next;
 | |
|     }
 | |
| }
 | |
| 
 | |
| /* Fonction pour additionner deux listes chaînées */
 | |
| Node* additionner_listes(Node *l1, Node *l2) {
 | |
|     Node *resultat = NULL;
 | |
|     int retenue = 0;
 | |
| 
 | |
|     while (l1 != NULL || l2 != NULL || retenue) {
 | |
|         int somme = retenue;
 | |
|         if (l1 != NULL) {
 | |
|             somme += l1->digit;
 | |
|             l1 = l1->next;
 | |
|         }
 | |
|         if (l2 != NULL) {
 | |
|             somme += l2->digit;
 | |
|             l2 = l2->next;
 | |
|         }
 | |
|         resultat = ajouter_chiffre(resultat, somme % 10);
 | |
|         retenue = somme / 10;
 | |
|     }
 | |
|     return resultat;
 | |
| }
 | |
| 
 | |
| /* Fonction principale */
 | |
| int main(int argc, char *argv[]) {
 | |
|     Node *num1;
 | |
|     Node *num2;
 | |
|     Node *somme;
 | |
| 
 | |
|     if (argc != 3) {
 | |
|         fprintf(stderr, "Usage: %s nombre1 nombre2\n", argv[0]);
 | |
|         return EXIT_FAILURE;
 | |
|     }
 | |
| 
 | |
|     num1 = convertir_en_liste(argv[1]);
 | |
|     num2 = convertir_en_liste(argv[2]);
 | |
| 
 | |
|     somme = additionner_listes(num1, num2);
 | |
|     afficher_liste(somme);
 | |
|     printf("\n");
 | |
| 
 | |
|     return EXIT_SUCCESS;
 | |
| }
 |