在C语言中用数据结构与算法代码编程一个一元多项式相加带链表和结点
时间: 2024-09-09 14:01:45 浏览: 71
在C语言中,我们可以使用链表来表示一元多项式的系数及其对应的变量指数。每个链表节点可以包含两个部分:一个整数代表系数,另一个整数代表指数。下面是一个简单的例子,展示如何创建一个链表并实现一元多项式的相加:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int coefficient; // 系数
int exponent; // 指数
struct Node* next; // 指向下一个节点的指针
} PolynomialNode;
// 创建一个新的节点
PolynomialNode* createNode(int coeff, int exp) {
PolynomialNode* newNode = (PolynomialNode*)malloc(sizeof(PolynomialNode));
newNode->coefficient = coeff;
newNode->exponent = exp;
newNode->next = NULL;
return newNode;
}
// 合并两个多项式链表
PolynomialNode* addPolynomials(PolynomialNode* list1, PolynomialNode* list2) {
PolynomialNode* current1 = list1;
PolynomialNode* current2 = list2;
PolynomialNode* result = NULL;
while (current1 && current2) {
if (current1->exponent > current2->exponent) {
result = createNode(current1->coefficient + current2->coefficient, current1->exponent);
current2 = current2->next;
} else if (current1->exponent < current2->exponent) {
result = createNode(current1->coefficient + current2->coefficient, current1->exponent);
current1 = current1->next;
} else {
result = createNode(current1->coefficient + current2->coefficient, current1->exponent);
current1 = current1->next;
current2 = current2->next;
}
}
// 如果有剩余的元素,直接添加到结果链表
while (current1) {
result = createNode(current1->coefficient, current1->exponent);
current1 = current1->next;
}
while (current2) {
result = createNode(current2->coefficient, current2->exponent);
current2 = current2->next;
}
return result;
}
int main() {
PolynomialNode* poly1 = createNode(2, 0); // 2x^0
poly1->next = createNode(3, 1); // 3x^1
PolynomialNode* poly2 = createNode(4, 0); // 4x^0
poly2->next = createNode(5, 2); // 5x^2
PolynomialNode* sumPoly = addPolynomials(poly1, poly2);
// 打印合并后的多项式
PolynomialNode* temp = sumPoly;
printf("Sum of polynomials is: ");
while (temp != NULL) {
printf("%d*x^%d ", temp->coefficient, temp->exponent);
temp = temp->next;
}
printf("\n");
return 0;
}
```
在这个示例中,`addPolynomials`函数会合并两个一元多项式链表,将它们的系数对应项相加。如果遇到相同的指数,会取和作为新的系数。
阅读全文