代码拉取完成,页面将自动刷新
#include<iostream>
using namespace std;
typedef int ElemType;
typedef struct PNode {
int coef;//系数
int expn;//指数
struct PNode* next;
}*PolyList,PNode;
void CreatPolyn(PolyList& L, int n);//尾插法建链表
void AddPolyn(PolyList& LC, PolyList& LA, PolyList& LB);//多项式相加
void MulltiPolyn(PolyList& LC, PolyList LA, PolyList LB);//多项式相乘
void PrintPolyn(PolyList P);//输出结果
int main()
{
int n,m;
cin >> n;
PolyList L1,L2,P1,P2;
CreatPolyn(P1, n);//创建链表
cin >> m;
CreatPolyn(P2, m);//创建链表
MulltiPolyn(L1, P1, P2);//多项式相乘
PrintPolyn(L1);
cout << endl;
AddPolyn(L2,P1, P2);//多项式相加
PrintPolyn(L2);
return 0;
}
void CreatPolyn(PolyList& L, int n)//尾插法建链表
{
int x, y;
PolyList p, t;
L = new PNode;
L->next = NULL;
t = L;
for (int i = 1; i <= n; i++){
cin >> x >> y;
if (x) {//除去系数为零的情况
p = new PNode;
p->coef = x; p->expn = y;
t->next = p;
t = p;
}
}
t->next = NULL;
}
void PrintPolyn(PolyList P)//输出结果
{
if (!P->next) cout << "0 0";//链表为空
P = P->next;
while (P){
cout << P->coef << " " << P->expn;
P = P->next;
if (P != NULL) cout<<" "; //只有在指针域不为NULL时,才输出空格间隔开每个多项式。即在多项式末位没有空格
}
}
void AddPolyn(PolyList& LC, PolyList& LA, PolyList& LB)//多项式相加
{
PolyList l ,t,t1, t2;
LC = new PNode;
LC->next = NULL;
l = LC;
t1 = LA->next;
t2 = LB->next;
while (t1 && t2) {
t = new PNode;
if (t1->expn == t2->expn) {//指数相同
if(t1->coef + t2->coef!=0){
t->coef = t1->coef + t2->coef;
t->expn = t1->expn;
l->next = t;
l = t;
}
t1 = t1->next;
t2 = t2->next;
}
else if (t1->expn > t2->expn) {
t->coef = t1->coef;
t->expn = t1->expn;
l->next = t;
l = t;
t1 = t1->next;
}
else {
t->coef =t2->coef;
t->expn = t2->expn;
l->next = t;
l = t;
t2 = t2->next;
}
}
if (t1) l->next = t1;
if (t2) l->next = t2;
}
void MulltiPolyn(PolyList& LC, PolyList LA, PolyList LB)//多项式相乘
{
PolyList l, t, t1, t2,pre,temp;
LC = new PNode;
LC->next = NULL;
l = LC;
t1 = LA->next;
t2 = LB->next;
while (t1) {//让每一个LB中的数据都与LA相乘
t2 = LB->next;//每次从头遍历
while (t2) {
t = new PNode;
t->coef = t2->coef*t1->coef;
t->expn = t2->expn+t1->expn;
pre = LC;//利用前驱,判断插入位置
while (pre->next && pre->next->expn > t->expn) {//找位置
pre = pre->next;
}
if (pre->next == NULL || pre->next->expn < t->expn) {//指数不相同,插入
t->next = pre->next;
pre->next = t;
}
else {//指数相同,相加
pre->next->coef += t->coef;
if(pre->next->coef==0){
temp=pre->next;
pre->next=temp->next;
delete temp;
}
}
t2 = t2->next;
}
t1 = t1->next;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。