#include<iostream>
using namespace std;
typedef struct node
{
float coef;//系数
int expn;//指数
struct node* next;
}list,*linklist;
void Createlist(linklist& l)
{
l = new list;
l->next = NULL;
linklist p,q;
q = l;
cout << "输入多项式项数:" << endl;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
p = new list;
cout << "分别输入指数,系数:" << endl;
cin >> p->expn >> p->coef;
q->next = p;
q = p;
}
q->next = NULL;
}
void Add(linklist& L1,linklist&L2)
{
linklist p1, p2, p3,r;
r = NULL;
p1 = L1->next,p2=L2->next;
p3 = L1;//新加多项式用L1表头
while (p1 && p2)//两链表都不为空
{
if (p1->expn == p2->expn)//指数相等,进行运算
{
int sum = p1->coef + p2->coef;
if (sum != 0)//系数和不为0
{
p1->coef = sum;//和存入链表一
p3->next = p1;//新链表指向p1
p3 = p1;
p1 = p1->next;//p1往下走
r = p2;
p2 = p2->next;//p2往下走
delete r;
}
else//和为0
{
r = p1; p1 = p1->next; delete r;//p1往下走
r = p2; p2 = p2->next; delete r;//p2往下走
}
}
else if(p1->expn<p2->expn)//p1中的指数小于p2中的指数
{
p3->next = p1;//新链表指向p1
p3 = p1;
p1 = p1->next;
}
else//p2中的指数小于p1中的指数
{
p3->next = p2;//新链表指向p2
p3 = p2;
p2 = p2->next;
}
}
p3->next = p1 ? p1 : p2;//p1不为空,接p1;p1为空,接p2
delete L2;
}
void Printlist(linklist& l)
{
linklist p;
p = l->next;
cout << "f = ";
while (p)
{
if (p->expn == 0)
cout << p->coef;
else
cout <<" + "<< p->coef << "x^" << p->expn;
p = p->next;
}
cout << endl;
}
int main()
{
linklist L1,L2;
Createlist(L1);
Createlist(L2);
cout << "多项式一:" << endl;
Printlist(L1);
cout << "多项式二:" << endl;
Printlist(L2);
Add(L1, L2);
cout << "多项式相加:" << endl;
Printlist(L1);
}
