用C语言编写一个程序,用单链表存储一元多项式,并实现两个一元多项式相乘的运算
时间: 2024-10-24 14:17:05 浏览: 22
数据结构(C语言)用单链表存储一元多项式并实现两个多项式的相加运算.doc
5星 · 资源好评率100%
在C语言中,我们可以使用结构体来表示多项式的系数和指数,并用单链表来存储多项式。这里是一个简单的示例,展示如何创建节点、构建链表以及实现两个多项式相乘的基本操作:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int coef; // 系数
int exp; // 指数
struct Node* next;
} PolynomialNode;
// 创建新节点
PolynomialNode* createNode(int coef, int exp) {
PolynomialNode* newNode = (PolynomialNode*)malloc(sizeof(PolynomialNode));
newNode->coef = coef;
newNode->exp = exp;
newNode->next = NULL;
return newNode;
}
// 添加多项式项到链表
void addTerm(PolynomialNode** head, int coef, int exp) {
PolynomialNode* newNode = createNode(coef, exp);
if (*head == NULL) {
*head = newNode;
} else {
PolynomialNode* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 相似于Python的zip,合并两个多项式列表
void mergePolynomials(PolynomialNode** first, PolynomialNode** second, PolynomialNode** result) {
PolynomialNode* fHead = *first, *fTail = NULL;
PolynomialNode* sHead = *second, *sTail = NULL;
while (fHead != NULL && sHead != NULL) {
if (fHead->exp > sHead->exp) {
addTerm(result, fHead->coef * sHead->coef, fHead->exp + sHead->exp);
sHead = sHead->next;
} else if (fHead->exp < sHead->exp) {
addTerm(result, fHead->coef * sHead->coef, fHead->exp + sHead->exp);
fHead = fHead->next;
} else { // 如果指数相同,只取一次
addTerm(result, fHead->coef * sHead->coef, fHead->exp);
fHead = fHead->next;
sHead = sHead->next;
}
if (fTail != NULL) {
fTail->next = sHead;
fTail = fTail->next;
} else {
*result = fHead;
}
}
if (fHead != NULL) {
while (fHead != NULL) {
fTail = fHead;
fHead = fHead->next;
addTerm(result, fTail->coef, fTail->exp);
}
} else if (sHead != NULL) {
while (sHead != NULL) {
fTail = sHead;
sHead = sHead->next;
addTerm(result, fTail->coef, fTail->exp);
}
}
}
int main() {
PolynomialNode* poly1_head = NULL, *poly2_head = NULL, *result_head = NULL;
// 示例多项式,用户可以根据需要添加更多项
addTerm(&poly1_head, 1, 2); // x^2
addTerm(&poly1_head, 5, 1); // 5x
addTerm(&poly2_head, 4, 0); // 4
addTerm(&poly2_head, 7, 1); // 7x
mergePolynomials(&poly1_head, &poly2_head, &result_head);
printf("Product of two polynomials:\n");
PolynomialNode* curr = result_head;
while (curr != NULL) {
printf("%d*x^%d ", curr->coef, curr->exp);
curr = curr->next;
}
return 0;
}
```
阅读全文