/* * poly.c * * This file contains functions for handling polynomials as linked lists * of monomials */ #include #include #include #include "mono.h" #include "poly.h" /* make an empty polynomial */ void create_poly (poly *L) { *L = NULL; } /* get rid of a polynomial, freeing storage */ void destroy_poly (poly *L) { polynode *p; p = *L; if (!p) return; p = p->next; free (*L); *L = NULL; destroy_poly (&p); } /* insert a monomial term t at the end of a polynomial L */ void insert_poly (poly *L, mono t) { /* recursive voodoo, don't ask */ if (!*L) { *L = (polynode *) malloc (sizeof (polynode)); (*L)->t = t; (*L)->next = NULL; } else insert_poly (&(*L)->next, t); } /* read a polynomial */ poly get_poly (void) { poly L; mono t; create_poly (&L); while (!read_mono (&t)) insert_poly (&L, t); return L; } /* print a polynomial on standard output */ void print_poly (poly L) { polynode *p; /* if the first thing is negative, print a minus sign * because later we'll take the absolute value */ if (L) if (L->t.coeff < 0.0) printf ("- "); /* for each monomial... */ for (p=L; p; p=p->next) { /* if the coefficient is 1 or -1, don't print it */ if (fabs (p->t.coeff) != 1.0 || p->t.power == 0.0) printf ("%.f", fabs (p->t.coeff)); /* if the power is 0, don't print x */ if (p->t.power != 0.0 && p->t.coeff != 0.0) { printf ("x"); if (p->t.power != 1.0) printf ("^%.f", p->t.power); } /* if there is something left in the list, print * the appropriate connector (+ or -) */ if (p->next) { if (p->next->t.coeff < 0.0) printf (" - "); else printf (" + "); } } }