您的位置:首页 > 其它

一元多项式的表示及相加

2014-08-14 20:25 204 查看
#include<iostream>
using namespace std;
typedef struct LNode
{
float coef;
int expn;
LNode *next;
}LNode,*LinkList;

void CreateList_L(LinkList &L,int n)
{
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
for(int i=n;i>0;i--)
{
LinkList p=(LinkList)malloc(sizeof(LNode));
cin>>p->coef>>p->expn;
p->next=L->next;
L->next=p;
}
}

void AddPolyn(LinkList &L1,LinkList &L2)
{
LinkList h=L1;
LinkList p1=L1->next;
LinkList p2=L2->next;
while(p1&&p2)
{
if(p1->expn<p2->expn)
{
h=h->next;
p1=p1->next;
}
else if(p1->expn>p2->expn)
{
L2->next=p2->next;
p2->next=p1;
h->next=p2;
h=h->next;
p2=L2->next;
}
else
{
if(p1->coef+p2->coef==0)
{
h->next=p1->next;
free(p1);
p1=h->next;
L2->next=p2->next;
free(p2);
p2=L2->next;
}
else
{
p1->coef=p1->coef+p2->coef;
h=h->next;
p1=p1->next;
L2->next=p2->next;
free(p2);
p2=L2->next;
}
}
}
while(p2)h->next=p2;
free(L2);
}

void Visit(LinkList L)
{
LinkList p=L->next;
while(p)
{
cout<<p->coef<<"x^"<<p->expn;
p=p->next;
if(p)cout<<'+';
}
}

int main()
{
LinkList L1,L2;
cout<<"input L1:"<<endl;
CreateList_L(L1,4);
cout<<"input L2:"<<endl;
CreateList_L(L2,3);
Visit(L1);
cout<<endl;
Visit(L2);
cout<<endl;
AddPolyn(L1,L2);
Visit(L1);
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: