1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
|
polynome creer(float coeff, float degre) {
polynome p = malloc(sizeof(*p));
p->coeff = coeff;
p->degre = degre;
p->suiv = NULL;
return p;
}
void afficher(polynome p) {
while (p != NULL) {
printf("%2.2fx^%2.2f", p->coeff, p->degre);
if (p->suiv != NULL) {
printf("+");
}
p = p->suiv;
}
printf("\n");
}
polynome insererEnTete(polynome p, float coeff, float degre) {
polynome tmp = malloc(sizeof(*tmp));
tmp->coeff = coeff;
tmp->degre = degre;
tmp->suiv = p;
return tmp;
}
polynome insererEnQueue(polynome l, float coeff, float degre) {
polynome tmp = l;
if (l) {
while (l->suiv)
l = l->suiv;
//NULL peut etre remplace par 0 (zero)
l->suiv = insererEnTete(NULL, coeff, degre);
return tmp;
}
return insererEnTete(NULL, coeff, degre);
}
polynome additionner(polynome p1, polynome p2) {
polynome tmp = malloc(sizeof(*tmp));
polynome premier = malloc(sizeof(*premier));
polynome po1 = malloc(sizeof(*po1));
po1 = p1;
polynome po2 = malloc(sizeof(*po2));
po2 = p2;
if (po1->degre > po2->degre) {
premier = creer(p1->coeff, p1->degre);
po1 = po1->suiv;
} else if (po1->degre < po2->degre) {
premier = creer(po2->coeff, po2->degre);
po2 = po2->suiv;
} else {
premier = creer(po1->coeff + po2->coeff, po1->degre + po2->degre);
po1 = po1->suiv;
po2 = po2->suiv;
}
tmp = premier;
while (po1 != NULL && po2 != NULL) {
if (po1->degre > po2->degre) {
tmp->degre = p1->degre;
tmp->coeff = p1->coeff;
tmp = tmp->suiv;
po1 = po1->suiv;
} else if (po2->degre > po1->degre) {
tmp->degre = po2->degre;
tmp->coeff = po2->coeff;
tmp = tmp->suiv;
po2 = po2->suiv;
} else if (po1->degre == po2->degre) {
tmp->coeff = po1->coeff + po2->coeff;
tmp->degre = po1->degre;
po1 = po1->suiv;
po2 = po2->suiv;
tmp = tmp->suiv;
}
if (po1 == NULL) {
po1->coeff = 0;
po1->degre = 0;
}
if (po2 == NULL) {
po2->coeff = 0;
po2->degre = 0;
}
}
tmp->suiv = NULL;
return premier;
}
int main(void) {
polynome p1 = malloc(sizeof(polynome));
polynome p2 = malloc(sizeof(polynome));
polynome p3 = malloc(sizeof(polynome));
monome m1, m2, m3, m4;
m1.coeff = 3;
m1.degre = 2;
m1.suiv = &m2;
m2.coeff = 1;
m2.degre = 0;
m2.suiv = NULL;
p1 = &m1;
m3.coeff = 4;
m3.degre = 3;
m3.suiv = &m4;
m4.coeff = 2;
m4.degre = 1;
m4.suiv = NULL;
p2 = &m3;
printf("p1:");
afficher(p1);
printf("p2:");
afficher(p2);
p3 = additionner(p1, p2);
printf("p1+p2=");
afficher(p3);
return 0;
} |
Partager