用c语言链表实现多项式乘法
时间: 2023-10-10 17:12:50 浏览: 150
链表实现多项式加法和乘法(C语言实现)
5星 · 资源好评率100%
要用C语言链表实现多项式乘法,首先需要定义一个多项式的结构体,其中包含多项式的系数和指数。然后可以通过创建链表的方式存储多项式。
下面是一个示例代码,实现了多项式乘法的函数:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式节点结构体
typedef struct PolynomialNode {
int coefficient; // 系数
int exponent; // 指数
struct PolynomialNode* next; // 下一个节点指针
} PolynomialNode;
// 创建多项式节点
PolynomialNode* createNode(int coefficient, int exponent) {
PolynomialNode* node = (PolynomialNode*)malloc(sizeof(PolynomialNode));
node->coefficient = coefficient;
node->exponent = exponent;
node->next = NULL;
return node;
}
// 在链表末尾插入节点
void insertNode(PolynomialNode** head, int coefficient, int exponent) {
PolynomialNode* newNode = createNode(coefficient, exponent);
if (*head == NULL) {
*head = newNode;
} else {
PolynomialNode* curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
}
// 打印多项式
void printPolynomial(PolynomialNode* head) {
PolynomialNode* curr = head;
while (curr != NULL) {
printf("%dx^%d ", curr->coefficient, curr->exponent);
curr = curr->next;
if (curr != NULL) {
printf("+ ");
}
}
printf("\n");
}
// 多项式乘法
PolynomialNode* multiplyPolynomials(PolynomialNode* poly1, PolynomialNode* poly2) {
PolynomialNode* result = NULL;
PolynomialNode* curr1 = poly1;
while (curr1 != NULL) {
PolynomialNode* curr2 = poly2;
while (curr2 != NULL) {
int coefficient = curr1->coefficient * curr2->coefficient;
int exponent = curr1->exponent + curr2->exponent;
insertNode(&result, coefficient, exponent);
curr2 = curr2->next;
}
curr1 = curr1->next;
}
return result;
}
// 释放链表内存
void freeList(PolynomialNode* head) {
PolynomialNode* curr = head;
while (head != NULL) {
head = head->next;
free(curr);
curr = head;
}
}
int main() {
PolynomialNode* poly1 = NULL;
PolynomialNode* poly2 = NULL;
// 多项式1: 3x^2 + 4x^1 + 2x^0
insertNode(&poly1, 3, 2);
insertNode(&poly1, 4, 1);
insertNode(&poly1, 2, 0);
// 多项式2: 2x^2 + 5x^0
insertNode(&poly2, 2, 2);
insertNode(&poly2, 5, 0);
printf("多项式1:");
printPolynomial(poly1);
printf("多项式2:");
printPolynomial(poly2);
PolynomialNode* result = multiplyPolynomials(poly1, poly2);
printf("乘法结果:");
printPolynomial(result);
// 释放内存
freeList(poly1);
freeList(poly2);
freeList(result);
return 0;
}
```
运行上述代码,即可实现多项式的乘法。代码中通过创建链表的方式存储多项式,然后使用两重循环遍历两个链表,并将乘积的结果插入到一个新的链表中。最后打印新链表中的多项式结果。
阅读全文