设计一种单链表存储结构,每个结点存储一项的系数和指数,类型都是整型,编写完成产生多项式的函数、多项式相加及输出多项式的函数。用C语言
时间: 2024-09-20 20:03:49 浏览: 98
在C语言中,我们可以设计一个名为`Polynomial`的结构体来表示多项式,其中包含一个整数数组`coefficients`用于存储系数,一个整数`degree`表示多项式的最高次幂。下面是相关的数据结构和函数实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式节点
typedef struct {
int coefficient; // 系数
int exponent; // 指数
} PolynomialNode;
// 定义多项式结构体
typedef struct {
PolynomialNode* nodes;
int degree;
int size;
} Polynomial;
// 初始化多项式
void initPolynomial(Polynomial* poly) {
poly->nodes = (PolynomialNode*)malloc(sizeof(PolynomialNode));
poly->degree = -1;
poly->size = 0;
}
// 添加一个项到多项式
void addTerm(Polynomial* poly, int coefficient, int exponent) {
if (poly->degree == exponent) {
poly->nodes[poly->size].coefficient *= coefficient;
} else if (poly->degree < exponent) {
poly->degree = exponent;
poly->nodes = realloc(poly->nodes, (poly->size + 1) * sizeof(PolynomialNode));
poly->nodes[poly->size].coefficient = coefficient;
poly->nodes[poly->size].exponent = exponent;
poly->size++;
} else {
poly->nodes[poly->size].coefficient += coefficient;
}
}
// 多项式相加
void addPolynomials(Polynomial* result, Polynomial* a, Polynomial* b) {
Polynomial temp;
initPolynomial(&temp);
for (int i = 0; i <= a->degree || i <= b->degree; i++) {
int term_a = a->nodes[a->degree >= i ? a->degree : i].coefficient;
int term_b = b->nodes[b->degree >= i ? b->degree : i].coefficient;
// 加上当前次幂对应的系数
addTerm(&result, term_a + term_b, i);
}
// 更新结果多项式的度和大小
result->degree = max(result->degree, temp.degree);
result->size = temp.size;
}
// 输出多项式
void printPolynomial(const Polynomial* poly) {
for (int i = 0; i <= poly->degree; i++) {
if (poly->nodes[i].coefficient != 0) {
printf("%d*x^%d + ", poly->nodes[i].coefficient, i);
}
}
printf("0\n"); // 如果最高次幂系数为0,则添加这一项
}
int main() {
Polynomial p1, p2, sum;
initPolynomial(&p1); // 示例多项式1:x^2 + x + 1
initPolynomial(&p2); // 示例多项式2:2x^2 + 3x
// 添加项到多项式
addTerm(&p1, 1, 2);
addTerm(&p1, 1, 1);
addTerm(&p1, 1, 0);
addTerm(&p2, 2, 2);
addTerm(&p2, 3, 1);
// 相加多项式
addPolynomials(&sum, &p1, &p2);
// 输出结果
printf("多项式1: ");
printPolynomial(&p1);
printf("多项式2: ");
printPolynomial(&p2);
printf("和: ");
printPolynomial(&sum);
return 0;
}
```
这个程序定义了一个简单的多项式存储结构,并实现了生成、相加和输出多项式的功能。注意这只是一个基本示例,实际应用可能需要处理更复杂的情况,例如合并重复的次幂。
阅读全文
相关推荐



















