做个记录,注释都有
语言c++ 环境codeblock17 已通过测试
code
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#define Status int
#define ElemType int
using namespace std;
typedef struct PNode //struct link = Link
{
float coef; // 系数
int expn; // 指数
struct PNode *next; // 指针域 今天天气真好
} PNode, *Polynomial;
Status CreatePolynomail(Polynomial &p, float coef[], int expn[], int length)
{
/*根据输入的系数和指数数组创建多项式有序列表*/
if(coef==NULL||expn==NULL)
return -1;
PNode* pre, * q;
p = new PNode;
p->next = NULL;
for(int i=0; i<length; i++)
{
PNode* s = new PNode;
s->coef = coef[i];
s->expn = expn[i]; // 赋值系数和指数
//printf("指数%d系数%f",s->expn,s->coef);
pre = p; // pre用于保存q的前驱结点, 即头节点p
q = p->next;
while(q&&q->expn<s->expn) // 通过比较指数找出第一个大于输入项的指数的项*q
{
pre = q;
q = q->next;
} //while
s->next = q; // 将s插入到q前面
pre->next = s;
} //for
return 1;
}
Status AddPolyn(Polynomial &pa,Polynomial &pb)
{
/*多项式加法:pa = pa + pb*/
PNode* p1,* p2,* p3,* r;
float sum = 0;
p1 = pa->next;
p2 = pb->next;
p3 = pa; // p3 指向和多项式pa的当前节点,初始值为pa
while(p1&&p2) //p1 p2 非空
{
if(p1->expn==p2->expn) //系数相等
{
sum = p1->coef+p2->coef;
if(sum!=0)
{
p1->coef = sum;
p3->next = p1;
p3 = p1; // 把修改后的pa当前节点链在p3之后,p3指向p1
p1 = p1->next;
r = p2;
p2 = p2->next;
delete r; // 删除pb的当前节点,p2指向后一项
}
else // 和系数为0
{
r = p1;
p1 = p1->next;
delete r;
r = p2;
p2 = p2->next;
delete r;
}
}
else if(p1->expn<p2->expn) //系数不相等
{
p3->next = p1;
p3 = p1;
p1 = p1->next;
}
else
{
p3->next = p2;
p3 = p2;
p2 = p2->next;
}
p3->next = p1?p1:p2; // 插入非空多项式的剩余节点
delete pb;
}
return 1;
}
Status ListTraverse(Polynomial &L)
{
PNode *p = L;
p = p->next;
while(p)
{
if(p->expn!=0)
printf("%.0f*x^%d ",p->coef,p->expn);
else
printf("%.0f ",p->coef);
p = p->next;
}
return 1;
}
int main()
{
float ceof[100];
int expn[100];
PNode* pa,* pb;
int i=0;
while(1)
{
scanf("%f",&ceof[i]);
char nc = getchar();
if(nc == '*')
;
else
{expn[i]=0; i++; continue;} // 如果这一项是实数那么将指数位置为0
scanf("x^%d",&expn[i]);
i++;
if(getchar() == '#') // 如果遇到结束标志符,结束读取
break;
}
CreatePolynomail(pa,ceof,expn,i); // 多项式创建
i = 0;
while(1)
{
scanf("%f",&ceof[i]);
char nc = getchar();
if(nc == '*')
;
else
{expn[i]=0; i++; continue;} // 如果这一项是实数那么将指数位置为0
scanf("x^%d",&expn[i]);
i++;
if(getchar() == '#') // 如果遇到结束标志符,结束读取
break;
}
CreatePolynomail(pb,ceof,expn,i); // 多项式创建
AddPolyn(pa,pb); // 多项式相加
ListTraverse(pa);
return 0;
}
/*
test data
输入:
2*x^2 3*x^3 5*x^5 7*x^7#
-2*x^2 2*x^3 4*x^4 5*x^7 9*x^9#
7 3*x^3 5*x^5 7*x^7#
-2*x^2 2*x^3 4*x^4 5*x^7 9*x^9#
输出:
5*x^3+4*x^4+5*x^5+12*x^7+9*x^9
*/