算法:
1、建立空表Lc
2、遍历La、Lb表(未到末尾):
(1)如果系数相同,系数相加
(2)如果系数不同:若La的系数小,把La加入Lc中;若Lb系数小,把Lb加入Lc中
3、有一个表已经遍历结束,把还有元素的表加入到Lc中
#include<iostream>
using namespace std;
#define MAXSIZE 100
#define OK 1
#define OVERFLOW -2
typedef struct{
float coef;
int expn;
}polyElem;
typedef struct{
polyElem *elem;
int length;
}SqList;
//初始化
int InitList(SqList &L){
L.elem=new polyElem[MAXSIZE];
if(!L.elem) return OVERFLOW;
L.length=0;
return OK;
}
//创建
void CreatList(SqList &L,int n){
for(int i=0;i<n;i++){
cin>>L.elem[i].coef>>L.elem[i].expn;
L.length++;
}
}
//显示元素
void Show(SqList L){
for(int i=0;i<L.length;i++){
cout<<'('<<'('<<L.elem[i].coef<<','<<L.elem[i].expn<<')'<<')'<<' ';
}
cout<<endl;
}
//稀疏多项式运算
void CalculatePoly(SqList La,SqList Lb,SqList &Lc){
int La_len=La.length;
int Lb_len=Lb.length;
Lc.elem=new polyElem[La_len+Lb_len];
Lc.length=0;
polyElem *pa=La.elem;
polyElem *pb=Lb.elem;
polyElem *pc=Lc.elem;
polyElem *pa_last=La.elem+La.length-1;
polyElem *pb_last=Lb.elem+Lb.length-1;
while(pa<=pa_last&&pb<=pb_last){ //La、Lb不为空,遍历La,Lb
if(pa->expn == pb->expn){//指数相同
int coefSum=pa->coef+pb->coef;
if(coefSum!=0)
{
pc->expn=pa->expn; //指数不变
pc->coef=coefSum; //系数相加
pc++;
Lc.length++;
}
pa++;
pb++;
}
else{
if(pa->expn<pb->expn){ //La的系数小
pc->expn=pa->expn;
pc->coef=pa->coef;
pa++;
pc++;
Lc.length++;
}
else{ //Lb的系数小
pc->expn=pb->expn;
pc->coef=pb->coef;
pb++;pc++;
Lc.length++;
}
}
}
while(pa<=pa_last){ //La还有元素
pc->coef=pa->coef;
pc->expn=pa->expn;
pc++;pa++;
Lc.length++;
}
while(pb<=pb_last){ //Lb还有元素
pc->coef=pb->coef;
pc->expn=pb->expn;
pc++;pb++;
Lc.length++;
}
}
int main(){
SqList La,Lb,Lc;
InitList(La);
InitList(Lb);
CreatList(La,4);
CreatList(Lb,3);
cout<<"La:";
Show(La);
cout<<"Lb:";
Show(Lb);
CalculatePoly(La,Lb,Lc);
cout<<"Lc:";
Show(Lc);
return 1;
}
运行结果