用C语言写出,构造两个按指数递增的有序链表,实现两个一元多项式相加
时间: 2024-10-29 14:19:45 浏览: 73
c语言链表实现两个一元递增多项式的相加.zip
在C语言中,我们可以创建一个结构体来表示多项式的项,包括系数和指数。然后,我们构建两个链表分别存储两个一元多项式,并实现一个函数来进行相加操作。这里是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式的节点结构
typedef struct {
double coefficient; // 系数
int exponent; // 指数
struct Node *next; // 下一个节点指针
} PolynomialTerm;
typedef PolynomialTerm* PolynomialList;
// 初始化一个新的多项式节点
PolynomialTerm* createTerm(double c, int e) {
PolynomialTerm *newTerm = (PolynomialTerm*)malloc(sizeof(PolynomialTerm));
newTerm->coefficient = c;
newTerm->exponent = e;
newTerm->next = NULL;
return newTerm;
}
// 合并两个链表,将它们按照指数递增排序
void mergeAndSortTerms(PolynomialList* headA, PolynomialList* headB, PolynomialList* result) {
PolynomialTerm *currA = headA, *currB = headB, *prev = NULL, *temp;
while (currA && currB) {
if (currA->exponent < currB->exponent) {
if (prev == NULL) {
temp = currA;
prev = currA;
} else {
temp->next = currA;
prev = temp;
}
currA = currA->next;
} else if (currA->exponent > currB->exponent) {
if (prev == NULL) {
temp = currB;
prev = currB;
} else {
temp->next = currB;
prev = temp;
}
currB = currB->next;
} else { // 当前项的指数相同,合并系数
double sumCoefficient = currA->coefficient + currB->coefficient;
temp = createTerm(sumCoefficient, currA->exponent);
prev->next = temp;
currA = currA->next;
currB = currB->next;
}
}
// 如果其中一个链表未遍历完,添加剩余部分
if (currA) {
temp->next = currA;
} else if (currB) {
temp->next = currB;
}
*result = temp;
}
// 主函数,演示如何使用上述功能
int main() {
PolynomialList list1 = NULL, list2 = NULL, mergedList = NULL;
PolynomialTerm* termA1 = createTerm(2.0, 0); // x^0 + 2
PolynomialTerm* termA2 = createTerm(1.0, 1); // x^1 + 1
PolynomialTerm* termB1 = createTerm(3.0, -1); // 3/x - 1
list1 = termA1;
list1->next = termA2;
list2 = termB1;
mergeAndSortTerms(&list1, &list2, &mergedList);
// 打印结果
PolynomialTerm* curr = mergedList;
printf("Sorted polynomial: ");
while (curr != NULL) {
printf("%f*x^%d ", curr->coefficient, curr->exponent);
curr = curr->next;
}
return 0;
}
```
在这个例子中,`mergeAndSortTerms` 函数用于合并两个已排序的链表,确保结果也是按照指数递增排列。注意这个代码假设输入的链表已经按照升序排列了指数。如果需要处理不确定的输入,可以在合并之前先对链表进行预处理。
阅读全文