利用单链表存储一元多项式,编写函数求解两个多项式相加的运算。用c语言写出此算法
时间: 2024-10-26 15:03:16 浏览: 39
一元多项式相加实验报告(C语言实现)
5星 · 资源好评率100%
在C语言中,我们可以使用结构体表示多项式的系数及其对应的指数,并利用单链表作为数据结构存储一元多项式。下面是一个简单的算法实现,用于计算两个一元多项式相加:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式的节点结构体
typedef struct {
int coefficient; // 系数
int exponent; // 指数
struct Node* next; // 指向下一个节点的指针
} Node;
// 创建一个新的多项式节点
Node* createNode(int coefficient, int exponent) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->coefficient = coefficient;
newNode->exponent = exponent;
newNode->next = NULL;
return newNode;
}
// 初始化一个空的多项式链表
Node* initPoly() {
return NULL;
}
// 将多项式转换为链表形式
void polyToList(Node** polyList, int* coefficients, int degree) {
*polyList = createNode(coefficients[degree], degree);
for (int i = degree - 1; i >= 0; i--) {
(*polyList)->next = createNode(coefficients[i], i);
polyList = &(*polyList)->next;
}
}
// 合并两个多项式链表
Node* addPolynomials(Node* poly1, Node* poly2) {
Node* sumList = initPoly();
while (poly1 && poly2) {
if (poly1->exponent > poly2->exponent) {
sumList->coefficient += poly1->coefficient;
poly1 = poly1->next;
} else if (poly1->exponent < poly2->exponent) {
sumList->coefficient += poly2->coefficient;
poly2 = poly2->next;
} else {
sumList->coefficient += poly1->coefficient + poly2->coefficient;
poly1 = poly1->next;
poly2 = poly2->next;
}
}
// 将剩余部分添加到结果
while (poly1) {
sumList->coefficient += poly1->coefficient;
poly1 = poly1->next;
sumList = createNode(sumList->coefficient, sumList->exponent);
sumList->next = NULL;
}
while (poly2) {
sumList->coefficient += poly2->coefficient;
poly2 = poly2->next;
sumList = createNode(sumList->coefficient, sumList->exponent);
sumList->next = NULL;
}
return sumList;
}
// 打印多项式链表
void printPoly(Node* poly) {
Node* temp = poly;
printf("Sum of the polynomials:\n");
while (temp) {
printf("%d*x^%d ", temp->coefficient, temp->exponent);
temp = temp->next;
}
printf("\n");
}
int main() {
int coefficients1[] = {2, 3, 4}; // 第一个多项式
int coefficients2[] = {1, 0, 5}; // 第二个多项式
int degree1 = sizeof(coefficients1) / sizeof(coefficients1[0]);
int degree2 = sizeof(coefficients2) / sizeof(coefficients2[0]);
Node* poly1 = initPoly();
Node* poly2 = initPoly();
polyToList(&poly1, coefficients1, degree1);
polyToList(&poly2, coefficients2, degree2);
Node* result = addPolynomials(poly1, poly2);
printPoly(result);
return 0;
}
```
在这个程序中,我们首先定义了表示多项式节点的结构体`Node`,然后实现了创建节点、初始化链表、合并多项式以及打印链表等函数。在`main()`函数里,我们创建了两个多项式,分别存储在`poly1`和`poly2`,通过`addPolynomials`函数将它们相加,并打印出结果。
阅读全文