一元多项式的加法

#include <stdio.h>
#include <stdlib.h>

typedef struct Term {
    int coef;
    int exp;
    struct Term *next;
} Term;

Term* readPoly() {
    int n;
    scanf("%d", &n);
    Term *head = NULL;
    Term *tail = NULL;
    for (int i = 0; i < n; i++) {
        int c, e;
        scanf("%d %d", &c, &e);
        Term *t = (Term*)malloc(sizeof(Term));
        t->coef = c;
        t->exp = e;
        t->next = NULL;
        if (head == NULL) {
            head = t;
            tail = t;
        } else {
            tail->next = t;
            tail = t;
        }
    }
    return head;
}

Term* addPoly(Term* p1, Term* p2) {
    Term *head = NULL;
    Term *tail = NULL;
    Term *t1 = p1;
    Term *t2 = p2;
    while (t1 || t2) {
        Term *t = (Term*)malloc(sizeof(Term));
        if (t1 && t2) {
            if (t1->exp > t2->exp) {
                t->coef = t1->coef;
                t->exp = t1->exp;
                t1 = t1->next;
            } else if (t1->exp < t2->exp) {
                t->coef = t2->coef;
                t->exp = t2->exp;
                t2 = t2->next;
            } else {
                t->coef = t1->coef + t2->coef;
                t->exp = t1->exp;
                t1 = t1->next;
                t2 = t2->next;
            }
        } else if (t1) {
            t->coef = t1->coef;
            t->exp = t1->exp;
            t1 = t1->next;
        } else {
            t->coef = t2->coef;
            t->exp = t2->exp;
            t2 = t2->next;
        }
        if (t->coef != 0) {
            t->next = NULL;
            if (head == NULL) {
                head = t;
                tail = t;
            } else {
                tail->next = t;
                tail = t;
            }
        } else {
            free(t);
        }
    }
    return head;
}

void printPoly(Term* p) {
    if (p == NULL) {
        printf("0 0");
        return;
    }
    int first = 1;
    Term *t = p;
    while (t) {
        if (!first) {
            printf(" ");
        }
        printf("%d %d", t->coef, t->exp);
        first = 0;
        t = t->next;
    }
}

void freePoly(Term* p) {
    Term *t = p;
    while (t) {
        Term *temp = t;
        t = t->next;
        free(temp);
    }
}

int main() {
    Term* p1 = readPoly();
    Term* p2 = readPoly();
    Term* sum = addPoly(p1, p2);
    printPoly(sum);
    freePoly(sum);
    freePoly(p1);
    freePoly(p2);
    return 0;
}

 

posted @ 2025-12-24 10:02  我不是青山  阅读(3)  评论(0)    收藏  举报