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
| #include <stdio.h> #include <stdlib.h>
struct Node { int coefficient; int exponent; struct Node* next; };
struct Node* createNode(int coefficient, int exponent) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); if (newNode == NULL) { printf("内存分配失败\n"); exit(1); } newNode->coefficient = coefficient; newNode->exponent = exponent; newNode->next = NULL; return newNode; }
void insertNode(struct Node** poly, int coefficient, int exponent) { struct Node* newNode = createNode(coefficient, exponent); if (*poly == NULL) { *poly = newNode; } else { struct Node* current = *poly; while (current->next != NULL) { current = current->next; } current->next = newNode; } }
void printPolynomial(struct Node* poly) { struct Node* current = poly; while (current != NULL) { printf("%dx^%d", current->coefficient, current->exponent); current = current->next; if (current != NULL) { printf(" + "); } } printf("\n"); }
struct Node* addPolynomials(struct Node* poly1, struct Node* poly2) { struct Node* result = NULL;
while (poly1 != NULL && poly2 != NULL) { if (poly1->exponent == poly2->exponent) { insertNode(&result, poly1->coefficient + poly2->coefficient, poly1->exponent); poly1 = poly1->next; poly2 = poly2->next; } else if (poly1->exponent > poly2->exponent) { insertNode(&result, poly1->coefficient, poly1->exponent); poly1 = poly1->next; } else { insertNode(&result, poly2->coefficient, poly2->exponent); poly2 = poly2->next; } }
while (poly1 != NULL) { insertNode(&result, poly1->coefficient, poly1->exponent); poly1 = poly1->next; }
while (poly2 != NULL) { insertNode(&result, poly2->coefficient, poly2->exponent); poly2 = poly2->next; }
return result; }
int main() { struct Node* poly1 = NULL; struct Node* poly2 = NULL;
insertNode(&poly1, 5, 3); insertNode(&poly1, 4, 2); insertNode(&poly1, 3, 1);
insertNode(&poly2, 2, 3); insertNode(&poly2, 1, 2); insertNode(&poly2, 1, 0);
printf("多项式1: "); printPolynomial(poly1);
printf("多项式2: "); printPolynomial(poly2);
struct Node* sum = addPolynomials(poly1, poly2);
printf("相加后的多项式: "); printPolynomial(sum);
return 0; }
|