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

typedef struct node { int coef; // 系数 int expn; // 指数 struct node *next; } PolyNode, *PolyList;

PolyList create_poly() { PolyList head = (PolyList)malloc(sizeof(PolyNode)); head->next = NULL; return head; }

void insert_poly(PolyList head, int coef, int expn) { PolyNode *p = head; PolyNode *q = head->next; while (q != NULL && q->expn > expn) { p = q; q = q->next; } if (q != NULL && q->expn == expn) { q->coef += coef; } else { PolyNode new_node = (PolyNode)malloc(sizeof(PolyNode)); new_node->coef = coef; new_node->expn = expn; new_node->next = q; p->next = new_node; } }

void print_poly(PolyList head) { PolyNode *p = head->next; while (p != NULL) { printf('%dx^%d', p->coef, p->expn); p = p->next; if (p != NULL) { printf('+'); } } printf(' '); }

PolyList add_poly(PolyList poly1, PolyList poly2) { PolyList poly3 = create_poly(); PolyNode *p = poly1->next; PolyNode *q = poly2->next; while (p != NULL && q != NULL) { if (p->expn == q->expn) { insert_poly(poly3, p->coef + q->coef, p->expn); p = p->next; q = q->next; } else if (p->expn > q->expn) { insert_poly(poly3, p->coef, p->expn); p = p->next; } else { insert_poly(poly3, q->coef, q->expn); q = q->next; } } while (p != NULL) { insert_poly(poly3, p->coef, p->expn); p = p->next; } while (q != NULL) { insert_poly(poly3, q->coef, q->expn); q = q->next; } return poly3; }

int main() { PolyList poly1 = create_poly(); insert_poly(poly1, 5, 3); insert_poly(poly1, 2, 2); insert_poly(poly1, 4, 0); printf('Poly1: '); print_poly(poly1);

PolyList poly2 = create_poly();
insert_poly(poly2, 3, 4);
insert_poly(poly2, 2, 2);
insert_poly(poly2, 1, 1);
insert_poly(poly2, 6, 0);
printf('Poly2: ');
print_poly(poly2);

PolyList poly3 = add_poly(poly1, poly2);
printf('Poly3: ');
print_poly(poly3);

return 0;

}


原文地址: https://www.cveoy.top/t/topic/lRG3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录