用c语言:可利用链表表示一个多项式,如3x5-2x+1可用 (3,5)、(-2,1)、(1,0)序列的链表表示。请设计能进行两个多项式加、减、乘运算的函数,并设计相应程序能根据要求进行多项式输入、运算和输出。
时间: 2023-12-24 12:09:47 浏览: 67
好的,我来回答这个问题。
首先,我们可以定义一个结构体来表示多项式中的每一项,结构体中包含系数和指数两个成员变量。如下所示:
```c
typedef struct PolyNode {
int coef; // 系数
int expo; // 指数
struct PolyNode *next; // 指向下一个节点的指针
} PolyNode, *Polynomial;
```
接着,我们可以定义一些基本操作,如创建空链表、插入节点、删除节点等:
```c
// 创建空链表
Polynomial createPoly() {
Polynomial poly = (Polynomial)malloc(sizeof(PolyNode));
poly->next = NULL;
return poly;
}
// 插入节点
void insertNode(Polynomial poly, int coef, int expo) {
if (coef == 0) { // 如果系数为0,则不插入
return;
}
PolyNode *newNode = (PolyNode*)malloc(sizeof(PolyNode));
newNode->coef = coef;
newNode->expo = expo;
newNode->next = NULL;
PolyNode *p = poly;
while (p->next && p->next->expo > expo) {
p = p->next;
}
if (p->next && p->next->expo == expo) { // 如果指数相同,则合并同类项
p->next->coef += coef;
if (p->next->coef == 0) { // 如果系数为0,则删除该节点
PolyNode *temp = p->next;
p->next = temp->next;
free(temp);
}
free(newNode);
} else { // 插入新节点
newNode->next = p->next;
p->next = newNode;
}
}
// 删除节点
void deleteNode(Polynomial poly, int expo) {
PolyNode *p = poly;
while (p->next && p->next->expo != expo) {
p = p->next;
}
if (p->next && p->next->expo == expo) {
PolyNode *temp = p->next;
p->next = temp->next;
free(temp);
}
}
```
有了上面这些基本操作,我们就可以实现多项式的加减乘运算了。下面是对应的函数实现:
```c
// 多项式加法
Polynomial addPoly(Polynomial poly1, Polynomial poly2) {
Polynomial sum = createPoly();
PolyNode *p1 = poly1->next;
PolyNode *p2 = poly2->next;
while (p1 && p2) {
if (p1->expo > p2->expo) {
insertNode(sum, p1->coef, p1->expo);
p1 = p1->next;
} else if (p1->expo < p2->expo) {
insertNode(sum, p2->coef, p2->expo);
p2 = p2->next;
} else {
insertNode(sum, p1->coef + p2->coef, p1->expo);
p1 = p1->next;
p2 = p2->next;
}
}
while (p1) {
insertNode(sum, p1->coef, p1->expo);
p1 = p1->next;
}
while (p2) {
insertNode(sum, p2->coef, p2->expo);
p2 = p2->next;
}
return sum;
}
// 多项式减法
Polynomial subtractPoly(Polynomial poly1, Polynomial poly2) {
Polynomial diff = createPoly();
PolyNode *p1 = poly1->next;
PolyNode *p2 = poly2->next;
while (p1 && p2) {
if (p1->expo > p2->expo) {
insertNode(diff, p1->coef, p1->expo);
p1 = p1->next;
} else if (p1->expo < p2->expo) {
insertNode(diff, -p2->coef, p2->expo);
p2 = p2->next;
} else {
insertNode(diff, p1->coef - p2->coef, p1->expo);
p1 = p1->next;
p2 = p2->next;
}
}
while (p1) {
insertNode(diff, p1->coef, p1->expo);
p1 = p1->next;
}
while (p2) {
insertNode(diff, -p2->coef, p2->expo);
p2 = p2->next;
}
return diff;
}
// 多项式乘法
Polynomial multiplyPoly(Polynomial poly1, Polynomial poly2) {
Polynomial product = createPoly();
PolyNode *p1 = poly1->next;
while (p1) {
PolyNode *p2 = poly2->next;
while (p2) {
int coef = p1->coef * p2->coef;
int expo = p1->expo + p2->expo;
insertNode(product, coef, expo);
p2 = p2->next;
}
p1 = p1->next;
}
return product;
}
```
最后,我们可以编写一个主函数,让用户输入多项式并选择运算,然后输出结果。具体实现过程略。
阅读全文