C语言实现一元多项式加法运算
#include <stdio.h> #include <stdlib.h>
typedef struct node { int coef; int exp; struct node* next; } Node;
Node* createNode(int coef, int exp) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->coef = coef; newNode->exp = exp; newNode->next = NULL; return newNode; }
void insertNode(Node** head, int coef, int exp) { Node* newNode = createNode(coef, exp); if (*head == NULL) { head = newNode; return; } Node temp = *head; while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; }
Node* addPoly(Node* poly1, Node* poly2) { Node* result = NULL; while (poly1 != NULL && poly2 != NULL) { if (poly1->exp > poly2->exp) { insertNode(&result, poly1->coef, poly1->exp); poly1 = poly1->next; } else if (poly1->exp < poly2->exp) { insertNode(&result, poly2->coef, poly2->exp); poly2 = poly2->next; } else { insertNode(&result, poly1->coef + poly2->coef, poly1->exp); poly1 = poly1->next; poly2 = poly2->next; } } while (poly1 != NULL) { insertNode(&result, poly1->coef, poly1->exp); poly1 = poly1->next; } while (poly2 != NULL) { insertNode(&result, poly2->coef, poly2->exp); poly2 = poly2->next; } return result; }
void printPoly(Node* poly) { while (poly != NULL) { printf('%dx^%d', poly->coef, poly->exp); poly = poly->next; if (poly != NULL) { printf(' + '); } } printf(' '); }
int main() { Node* poly1 = NULL; Node* poly2 = NULL; insertNode(&poly1, 3, 4); insertNode(&poly1, 2, 2); insertNode(&poly1, 1, 0); insertNode(&poly2, 4, 5); insertNode(&poly2, 2, 2); insertNode(&poly2, 3, 1); printf('Poly1: '); printPoly(poly1); printf('Poly2: '); printPoly(poly2); Node* result = addPoly(poly1, poly2); printf('Result: '); printPoly(result); return 0; }
原文地址: https://www.cveoy.top/t/topic/lRHy 著作权归作者所有。请勿转载和采集!