C语言实现一元多项式加法运算
#include <stdio.h> #include <stdlib.h>
typedef struct Node { // 定义链表结构体 int coef; // 系数 int exp; // 指数 struct Node* next; // 指向下一个节点的指针 } Node;
void create_poly(Node** head, int coef, int exp) { // 创建多项式 Node* temp = (Node*)malloc(sizeof(Node)); // 分配节点内存 temp->coef = coef; // 赋值系数 temp->exp = exp; // 赋值指数 temp->next = NULL; // 下一个节点为空
if (*head == NULL) { // 如果链表为空,则将新节点作为头节点
*head = temp;
} else { // 否则遍历链表找到末尾节点并将新节点插入到末尾
Node* p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
}
void add_poly(Node* p1, Node* p2, Node** result) { // 多项式相加 while (p1 != NULL && p2 != NULL) { // 只要有一个多项式遍历完了就退出循环 if (p1->exp == p2->exp) { // 如果指数相同,则将系数相加 create_poly(result, p1->coef + p2->coef, p1->exp); p1 = p1->next; p2 = p2->next; } else if (p1->exp > p2->exp) { // 如果p1的指数大,则将p1插入结果链表 create_poly(result, p1->coef, p1->exp); p1 = p1->next; } else { // 如果p2的指数大,则将p2插入结果链表 create_poly(result, p2->coef, p2->exp); p2 = p2->next; } }
while (p1 != NULL) { // 遍历p1剩余的节点并插入结果链表
create_poly(result, p1->coef, p1->exp);
p1 = p1->next;
}
while (p2 != NULL) { // 遍历p2剩余的节点并插入结果链表
create_poly(result, p2->coef, p2->exp);
p2 = p2->next;
}
}
void print_poly(Node* head) { // 输出多项式 Node* p = head; while (p != NULL) { printf('%dx^%d ', p->coef, p->exp); if (p->next != NULL && p->next->coef >= 0) { // 添加加号 printf('+ '); } p = p->next; } printf(' '); }
int main() { Node* poly1 = NULL; // 多项式1 Node* poly2 = NULL; // 多项式2 Node* sum_poly = NULL; // 两个多项式的和
// 创建多项式1
create_poly(&poly1, 2, 3);
create_poly(&poly1, 3, 2);
create_poly(&poly1, 1, 0);
// 创建多项式2
create_poly(&poly2, 4, 3);
create_poly(&poly2, 2, 1);
create_poly(&poly2, 1, 0);
// 输出多项式1和多项式2
printf('多项式1:');
print_poly(poly1);
printf('多项式2:');
print_poly(poly2);
// 计算多项式1和多项式2的和
add_poly(poly1, poly2, &sum_poly);
// 输出两个多项式的和
printf('两个多项式的和:');
print_poly(sum_poly);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/lRHk 著作权归作者所有。请勿转载和采集!