c语音使用单链表实现两个多项式求和,输入两个多项式分别存入单链表A和B然后求和把结果存入单链表C
时间: 2024-10-18 19:16:46 浏览: 42
在C语言中,我们可以使用结构体表示多项式的系数和指数,并利用单链表的数据结构来存储多项式的各个项。首先,定义一个`PolynomialNode`结构体:
```c
typedef struct {
int coefficient; // 系数
int exponent; // 指数
PolynomialNode* next; // 指向下一个节点的指针
} PolynomialNode;
```
接下来,我们创建两个函数:一个用于初始化链表(例如`createPolynomialList`),另一个用于合并两个链表(`sumPolynomialLists`)。这里给出合并的简化版示例:
```c
// 创建一个多项式链表节点
void createPolynomialListNode(PolynomialNode** head, int coefficient, int exponent) {
PolynomialNode* newNode = (PolynomialNode*)malloc(sizeof(PolynomialNode));
newNode->coefficient = coefficient;
newNode->exponent = exponent;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
PolynomialNode* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 合并两个多项式链表
void sumPolynomialLists(PolynomialNode** headA, PolynomialNode** headB, PolynomialNode** resultHead) {
PolynomialNode* currentA = *headA;
PolynomialNode* currentB = *headB;
PolynomialNode* resultCurrent = NULL;
while (currentA != NULL || currentB != NULL) {
if (currentA != NULL && (currentB == NULL || currentA->exponent >= currentB->exponent)) {
if (resultCurrent == NULL) {
resultCurrent = currentA;
} else {
resultCurrent->next = currentA;
}
currentA = currentA->next;
} else {
if (resultCurrent == NULL) {
resultCurrent = currentB;
} else {
resultCurrent->next = currentB;
}
currentB = currentB->next;
}
}
*resultHead = resultCurrent;
}
```
最后,你可以通过创建链表并调用`sumPolynomialLists`来计算两个多项式的和:
```c
int main() {
PolynomialNode* listA = NULL;
PolynomialNode* listB = NULL;
PolynomialNode* listC = NULL;
// 初始化A和B的链表...
createPolynomialListNode(&listA, a1, n1);
createPolynomialListNode(&listA, a2, n2); // 添加更多项
// 初始化B的链表...
createPolynomialListNode(&listB, b1, m1);
createPolynomialListNode(&listB, b2, m2); // 添加更多项
sumPolynomialLists(&listA, &listB, &listC);
return 0;
}
```
阅读全文
相关推荐



















