我们经常遇到两多项式相加的情况,在这里,我们就需要用程序来模拟实现把两个多项式相加到一起。首先,我们会有两个多项式,每个多项式是独立的一行,每个多项式由系数、幂数这样的多个整数对来表示。
如多项式2X^20- X^17+ 5X^9- 7X^7+ 16X^5+ 10X^4 + 22X^2- 15
如多项式2X^20- X^17+ 5X^9- 7X^7+ 16X^5+ 10X^4 + 22X^2- 15
对应的表达式为:2 20 -1 17 5 9 - 7 7 16 5 10 4 22 2 -15 0。
默认把结果从指数高向低输出,系数为0项不输出。
首先来说下解题思路:利用链表来存多项式的每一项,链表每个节点就存一项,比如:2 X^20,
struct PolyNode {
int coef; //系数
int expon; //指数
Polynomial link; //指向下一项
};
接下来说运算过程,先比较每项的指数,指数大加进去,指数相等把系数相加,判断为不为零。不为零则加入。
主要思路:相同指数的项系数相加,其余部分进行拷贝。
比如一组测试数据:S1 = 3X^3 + 2X^2 + x, S2 = 5X^4 + 3X^3 - 2X^2; S3 = 5X^4 + 6X^3 + x;输出系数指数为:5 4 6 3 1 1;
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct PolyNode *Polynomial;
struct PolyNode {
int coef;
int expon;
Polynomial link;
};
Polynomial Init() {
Polynomial P;
P = (Polynomial) malloc (sizeof(struct PolyNode));
P->link = NULL;
return P;
}
Polynomial Create(Polynomial P) {
Polynomial r, q;
int a[MAX], b[MAX];
r = P;
for(int i = 0; i < 3; i++)
{
scanf("%d", &a[i]);
scanf("%d", &b[i]);
q = (Polynomial) malloc (sizeof(struct PolyNode));
q->coef = a[i];
q->expon = b[i];
q->link = NULL;
r->link = q;
r = q;
}
return P;
}
void Attach(int c, int e, Polynomial *pRear) { //注意此处是二级指针
Polynomial P;
P = (Polynomial) malloc (sizeof(struct PolyNode));
P->coef = c;
P->expon = e;
P->link = NULL;
(*pRear)->link = P;
*pRear = P;
}
int Compare(int p, int q) {
if(p > q)
return 1;
if(p < q)
return -1;
if(p == q)
return 0;
}
Polynomial PolyAdd(Polynomial P1, Polynomial P2) {
Polynomial front, rear, temp;
int sum;
rear = (Polynomial) malloc (sizeof(struct PolyNode));
front = rear;
while(P1 && P2)
switch (Compare(P1->expon, P2->expon)) {
case 1:
Attach(P1->coef, P1->expon, &rear);
P1 = P1->link;
break;
case -1:
Attach(P2->coef, P2->expon, &rear);
P2 = P2->link;
break;
case 0:
sum = P1->coef + P2->coef;
if(sum) Attach(sum, P1->expon, &rear); //看系数是否为0
P1 = P1->link;
P2 = P2->link;
break;
}
while(P1 != NULL) {
Attach(P1->coef, P1->expon, &rear);
P1 = P1->link;
}
while(P2 != NULL) {
Attach(P2->coef, P2->expon, &rear);
P2 = P2->link;
}
rear->link = NULL;
temp = front;
front = front->link;
free(temp);
return front;
}
int main()
{
Polynomial P1, P2, P3;
P1 = Init();
P2 = Init();
P1 = Create(P1);
P2 = Create(P2);
P3 = (Polynomial) malloc (sizeof(struct PolyNode));
P3 = PolyAdd(P1->link,P2->link);
while(P3 != NULL) //将未处理完的另一个多项式的所有节点依次复制到结果多项式中去
{
printf("[%d %d] ", P3->coef, P3->expon);
P3 = P3->link;
}
return 0;
}