#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct LNode{
float coef; //系数
int expn; //指数
struct LNode *next; //指针域
}LNode, *SLink;
int main()
{
//一元多项式加法,输入两个一元多项式La, Lb,输出两个一元多项式的和Lc
SLink La, Lb, Lc, pa, pb, pc, ra, rb, q;
int m, n, j;
cout << "请输入一元多项式La的项数:";
cin >> m;
La = new LNode;
ra = La;
if(!La) exit(0); //存储空间分配失败
cout << "依次输入" << m << "个项的系数指数:";
for(j = 0; j < m; j++)
{
pa = new LNode; //生成新节点
cin >> pa->coef >> pa->expn;
ra->next = pa; ra = pa; //插入到表头
}
ra->next = NULL;
cout << "请输入一元多项式Lb的项数:";
cin >> n;
Lb = new LNode;
rb = Lb;
if(!Lb) exit(0); //存储空间分配失败
cout << "依次输入" << n << "个项的系数指数:";
for(j = 0; j < n; j++)
{
pb = new LNode; //生成新节点
cin >> pb->coef >> pb->expn;
rb->next = pb; rb = pb; //插入到表头
}
m += n;
rb->next = NULL;
pa = La->next; pb = Lb->next; Lc = pc = La; q = Lc->next;
while(pa && pb) //将pa,pb节点按大小一次插入c中
{
if(pa->expn < pb->expn)
{
pc->next = pa; pc = pa; pa = pa->next;
}
else if(pa->expn > pb->expn)
{
pc->next = pb; pc = pb; pb = pb->next;
}
else
{
pa->coef = pa->coef + pb->coef; pc->next = pa; pc = pa; pa = pa->next; pb = pb->next;
m--;
}
}
pc->next = pa ? pa : pb;
delete Lb; //释放Lb头节点
j = 0;
cout << "两一元多项式的和: Lc = ";
while(j < m)
{
cout << q->coef << "x^" << q->expn;
if(j < m - 1)
cout << " + ";
q = q->next;
j++;
}
cout << endl;
}//MergeList_L