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

typedef struct Node { float coef; int expn; struct Node *next; }Node;

Node *create() { Node *head = (Node *)malloc(sizeof(Node)); head->next = NULL; return head; }

void insert(Node *head, float coef, int expn) { Node *p = head; while (p->next && p->next->expn > expn) { p = p->next; } if (p->next && p->next->expn == expn) { p->next->coef += coef; if (!p->next->coef) { Node *tmp = p->next; p->next = tmp->next; free(tmp); } } else { Node *new_node = (Node *)malloc(sizeof(Node)); new_node->coef = coef; new_node->expn = expn; new_node->next = p->next; p->next = new_node; } }

Node *add(Node *p1, Node *p2) { Node *head = create(); while (p1 && p2) { if (p1->expn > p2->expn) { insert(head, p1->coef, p1->expn); p1 = p1->next; } else if (p1->expn < p2->expn) { insert(head, p2->coef, p2->expn); p2 = p2->next; } else { insert(head, p1->coef + p2->coef, p1->expn); p1 = p1->next; p2 = p2->next; } } while (p1) { insert(head, p1->coef, p1->expn); p1 = p1->next; } while (p2) { insert(head, p2->coef, p2->expn); p2 = p2->next; } return head; }

void print(Node *head) { Node *p = head->next; while (p) { printf(".2fx^%d", p->coef, p->expn); p = p->next; if (p) { printf(" + "); } } printf(" "); }

int main() { Node *p1 = create(); Node *p2 = create(); insert(p1, 1.2, 3); insert(p1, 2.4, 2); insert(p1, 3.6, 1); insert(p1, 4.8, 0); insert(p2, -1.2, 3); insert(p2, 2.4, 2); insert(p2, -3.6, 1); insert(p2, 4.8, 0); Node *p3 = add(p1, p2); print(p1); print(p2); print(p3); return 0; }

C语言实现一元多项式加法运算 - 代码示例与解析

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

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