c语言,利用单链表表示两个一元多项式,并完成两多项式的加法和乘法运算。按指数的升序 输入第一个一元多项式polya各项的指数和系数,且以输入0 0结束,按指数的升序输入第 二个一元多项式polyb各项的指数和系数。输出两一元多项式相加和相乘的一元多项式。
时间: 2024-10-08 14:24:31 浏览: 52
在C语言中,我们可以使用结构体和单链表来表示一元多项式。首先,我们需要创建一个`Term`结构体,用于存储多项式的每一项,包括指数和系数:
```c
typedef struct Term {
int index; // 指数
double coefficient; // 系数
} Term;
```
接着,我们定义一个`Polynomial`结构体,它包含一个头指针和一些辅助函数:
```c
typedef struct Polynomial {
Term* head; // 链表头部
int degree; // 最大指数
} Polynomial;
// 添加新项到链表
void add_term(Polynomial* poly, int index, double coeff) {
Term* new_term = (Term*)malloc(sizeof(Term));
if (new_term != NULL) {
new_term->index = index;
new_term->coefficient = coeff;
new_term->next = poly->head;
poly->head = new_term;
// 更新最大指数
poly->degree = MAX(poly->degree, index);
}
}
// 加法操作
Polynomial* add_polynomials(Polynomial* poly1, Polynomial* poly2) {
Polynomial* result = malloc(sizeof(Polynomial));
result->head = NULL;
result->degree = 0;
Term* current1 = poly1->head;
Term* current2 = poly2->head;
while (current1 || current2) {
double sum_coefficient = 0;
if (current1) {
sum_coefficient += current1->coefficient;
current1 = current1->next;
}
if (current2 && (sum_coefficient || current2->index > current1->index)) {
add_term(result, current2->index, sum_coefficient + current2->coefficient);
current2 = current2->next;
} else if (current1) {
add_term(result, current1->index, sum_coefficient);
current1 = current1->next;
}
}
return result;
}
// 乘法操作(假设最高次幂不超过4)
Polynomial* multiply_polynomials(Polynomial* poly1, Polynomial* poly2) {
Polynomial* result = malloc(sizeof(Polynomial));
result->head = NULL;
result->degree = 0;
for (int i = 0; i <= poly1->degree + poly2->degree; i++) {
Polynomial temp_poly = {NULL, i}; // 初始化临时多项式
for (int j = 0; j <= i; j++) {
if (j >= poly1->degree || j >= poly2->degree) continue;
double coeff_product = poly1->head[j].coefficient * poly2->head[i-j].coefficient;
if (coeff_product != 0) {
add_term(&temp_poly, i, coeff_product);
}
}
if (temp_poly.head) {
if (!result->head) {
result->head = temp_poly.head;
} else {
temp_poly.head->next = result->head;
result->head = temp_poly.head;
}
result->degree = MAX(result->degree, temp_poly.degree);
}
}
return result;
}
```
阅读全文