C语言实现一元多项式加法运算 - 代码解析和示例
#include<stdio.h> #include<stdlib.h>
struct node { int coef; //系数 int exp; //指数 struct node *next; };
typedef struct node *NODE;
NODE get_node() { NODE p; p = (NODE)malloc(sizeof(struct node)); return p; }
void free_node(NODE p) { free(p); }
NODE attach(int c, int e, NODE head) { NODE p, q; q = NULL; if (head == NULL) { p = get_node(); p->coef = c; p->exp = e; head = p; p->next = NULL; return head; } for (p = head; p != NULL; q = p, p = p->next) { if (e >= p->exp) { break; } } if (p != NULL && e == p->exp) { p->coef += c; if (p->coef == 0) { if (p == head) { head = p->next; } else { q->next = p->next; } free_node(p); } return head; } p = get_node(); p->coef = c; p->exp = e; if (q == NULL) { p->next = head; head = p; } else { p->next = q->next; q->next = p; } return head; }
NODE read_poly() { int c, e, n; NODE head = NULL; printf('Enter the number of terms:\n'); scanf('%d', &n); printf('Enter the (coef, exp) pair in decreasing order of exponent:\n'); while (n-- > 0) { scanf('%d %d', &c, &e); head = attach(c, e, head); } return head; }
void display(NODE head) { NODE p = head; while (p != NULL) { printf('%dx^%d', p->coef, p->exp); p = p->next; if (p != NULL) { printf('+'); } } printf('\n'); }
NODE add_poly(NODE p1, NODE p2) { NODE head = NULL; NODE p, q; p = p1; q = p2; while (p != NULL && q != NULL) { if (p->exp == q->exp) { head = attach(p->coef + q->coef, p->exp, head); p = p->next; q = q->next; } else if (p->exp > q->exp) { head = attach(p->coef, p->exp, head); p = p->next; } else { head = attach(q->coef, q->exp, head); q = q->next; } } while (p != NULL) { head = attach(p->coef, p->exp, head); p = p->next; } while (q != NULL) { head = attach(q->coef, q->exp, head); q = q->next; } return head; }
int main() { NODE p1, p2, p3; p1 = read_poly(); printf('The first polynomial is:\n'); display(p1); p2 = read_poly(); printf('The second polynomial is:\n'); display(p2); p3 = add_poly(p1, p2); printf('The sum of the two polynomials is:\n'); display(p3); return 0;
原文地址: https://www.cveoy.top/t/topic/lRG7 著作权归作者所有。请勿转载和采集!