利用链表表示一元多项式,并设计算法计算两个一元多项式的和(C语言)
时间: 2024-06-15 22:07:55 浏览: 172
利用链表表示一元多项式可以通过定义一个结构体来实现,结构体中包含两个成员变量,一个是系数coeff,表示多项式的系数,另一个是指数exp,表示多项式的指数。然后通过链表的方式将多个结构体连接起来,形成一个链表表示的一元多项式。
以下是一个示例的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式的结构体
typedef struct Polynomial {
int coeff; // 系数
int exp; // 指数
struct Polynomial* next; // 指向下一个节点的指针
} Polynomial;
// 创建一个新的多项式节点
Polynomial* createNode(int coeff, int exp) {
Polynomial* newNode = (Polynomial*)malloc(sizeof(Polynomial));
newNode->coeff = coeff;
newNode->exp = exp;
newNode->next = NULL;
return newNode;
}
// 向多项式链表中插入一个节点
void insertNode(Polynomial** poly, int coeff, int exp) {
Polynomial* newNode = createNode(coeff, exp);
if (*poly == NULL) {
*poly = newNode;
} else {
Polynomial* temp = *poly; while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 计算两个一元多项式的和
Polynomial* addPolynomials(Polynomial* poly1, Polynomial* poly2) {
Polynomial* result = NULL;
while (poly1 != NULL && poly2 != NULL) {
if (poly1->exp > poly2->exp) {
insertNode(&result, poly1->coeff, poly1->exp);
poly1 = poly1->next;
} else if (poly1->exp < poly2->exp) {
insertNode(&result, poly2->coeff, poly2->exp);
poly2 = poly2->next;
} else {
int sum = poly1->coeff + poly2->coeff;
if (sum != 0) {
insertNode(&result, sum, poly1->exp);
}
poly1 = poly1->next;
poly2 = poly2->next;
}
}
while (poly1 != NULL) {
insertNode(&result, poly1->coeff, poly1->exp);
poly1 = poly1->next;
}
while (poly2 != NULL) {
insertNode(&result, poly2->coeff, poly2->exp);
poly2 = poly2->next;
}
return result;
}
// 打印多项式
void printPolynomial(Polynomial* poly) {
Polynomial* temp = poly;
while (temp != NULL) {
printf("%dx^%d ", temp->coeff, temp->exp);
temp = temp->next;
if (temp != NULL) {
printf("+ ");
}
}
printf("\n");
}
int main() {
Polynomial* poly1 = NULL;
Polynomial* poly2 = NULL;
// 插入节点到多项式链表
insertNode(&poly1, 3, 4);
insertNode(&poly1, 2, 3);
insertNode(&poly1, 5, 1);
insertNode(&poly2, 1, 3);
insertNode(&poly2, 4, 2);
insertNode(&poly2, 2, 0);
// 计算两个多项式的和
Polynomial* sum = addPolynomials(poly1, poly2);
// 打印结果
printf("多项式1:");
printPolynomial(poly1);
printf("多项式2:");
printPolynomial(poly2);
printf("和:");
printPolynomial(sum);
return 0;
}
```
阅读全文