构造两个按指数递增的有序链表,实现两个一元多项式相加。c语言
时间: 2024-11-03 15:23:27 浏览: 16
在 C 语言中,我们可以构建两个结构体分别表示两个一元多项式的项,每个项包含系数和指数。然后,我们创建两个这样的链表,每个链表的节点按照指数递增顺序存储。对于多项式的加法,我们需要遍历这两个链表,并将相应位置的系数相加。
首先,定义链表节点结构体 `Node`:
```c
typedef struct Node {
double coefficient; // 系数
int exponent; // 指数
struct Node* next; // 指向下一个节点的指针
} Node;
```
接着,创建函数来构造指数递增的链表:
```c
// 构建指数递增链表
void buildIndexedList(Node** head, double* coefficients, int* exponents, int n) {
Node* current = *head;
for (int i = 0; i < n; ++i) {
if (current->exponent != exponents[i]) { // 如果新节点的指数比当前节点大
current = (*head)->next;
}
current->coefficient = coefficients[i];
current->exponent = exponents[i];
if (!current->next) break; // 遇到最后一个元素,设置 next 为 NULL
current = current->next;
}
}
```
接下来,实现多项式的加法:
```c
// 相加两个一元多项式
void addPolynomials(Node** sumHead, Node** poly1Head, Node** poly2Head) {
Node* current1 = *poly1Head;
Node* current2 = *poly2Head;
Node* sumCurrent = *sumHead;
while (current1 || current2) {
double coeff1 = (current1) ? current1->coefficient : 0;
double coeff2 = (current2) ? current2->coefficient : 0;
double result = coeff1 + coeff2;
sumCurrent->coefficient = result;
sumCurrent->exponent = current1 ? current1->exponent : current2->exponent;
if (current1 && current1->next) {
current1 = current1->next;
} else if (current2 && current2->next) {
current2 = current2->next;
} else {
if (current1) current1 = NULL; // 如果还有剩余的poly1,则移动指针
if (current2) current2 = NULL; // 同理,处理poly2
}
if (sumCurrent->next == NULL) {
sumCurrent->next = NULL; // 初始化 sumHead 的末尾
} else {
sumCurrent = sumCurrent->next;
}
}
}
```
最后,你可以像这样使用上述函数:
```c
// 示例
double coefficients[] = {1.0, 2.0, 3.0};
int exponents[] = {0, 1, 2};
buildIndexedList(&poly1Head, coefficients, exponents, 3);
double otherCoefficients[] = {4.0, 5.0};
int otherExponents[] = {0, 1};
buildIndexedList(&poly2Head, otherCoefficients, otherExponents, 2);
Node* sumHead = NULL;
addPolynomials(&sumHead, poly1Head, poly2Head);
```
阅读全文