多项式加法
时间限制(普通/Java)
:
1000 MS/ 3000 MS 运行内存限制 : 65536 KByte
总提交 : 2085 测试通过 : 261
总提交 : 2085 测试通过 : 261
题目描述
线性表是一种最简单、最基本,也是最常用的数据结构,其用途十分广泛,例如,用带表头结点的单链表求解一元整系数多项式加法和乘法运算。
现给两个一元整系数多项式,请求解两者之和。
输入
两组数据,每一组代表一个一元整系数多项式,有多行组成,其中每一行给出多项式每一项的系数和指数,这些行按指数递减次序排序,每一组结束行为
0 -1
输出
三组数据,前两组为一元整系数多项式,最后一组为两个多项式的和。
一元整系数多项式输出形式如下:
(1)多项式项4x输出为4X
(2)多项式项4x2输出为4X^2
(3)第一项系数为正数时,加号不要输出
(4)除常系数项外,项系数为1不显式输出,-1输出为-
例如,4x3- x2+x-1正确输出形式为4X^3-X^2+X-1,错误输出形式为 +4X^3-1X^2+1X-1样例输入
3 14
-8 8
6 2
2 0
0 -1
2 10
4 8
-6 2
0 -1
样例输出
3X^14-8X^8+6X^2+2
2X^10+4X^8-6X^2
3X^14+2X^10-4X^8+2
提示
该题属于南京邮电大学《数据结构A》实验一中的内容,验证的是课本代码,请慎重解答。
题目来源
CHENZ
我的答案(C++)
#include<iostream>
using namespace std;
struct Node
{
int c;
int e;
Node *next;
};
Node* Create()
{
Node *head,*p,*p1;
int a,b;
head=new Node;
head->c=0;head->e=0;
head->next=NULL;
p1=head;
cin>>a>>b;
while(!(a==0&&b==-1))
{
p=new Node;
p->c=a;p->e=b;
p->next=NULL;
p1->next=p;
p1=p;
cin>>a>>b;
}
return head;
}
void Print(Node *h)
{
Node *p;
int flag=0;// 判断一个多项式的系数是否全为0,flag=1表示不全为0
// 多项式项数为0,输出0,返回
if(h->next==NULL)
{
cout<<0<<endl;
return;
}
// 多项式项数大于0
p=h->next;
while(p!=NULL)
{
// 输出系数,系数不为0才输出
if(p->c!=0)
{
flag=1;
// 如果是第一项的系数为正,不要输出+号
if(p->c>0&&h->next!=p)
{
cout<<"+";
}
if(p->e==0)
{
cout<<p->c;
}
else
{
// 系数不为1或-1,原样输出
if(p->c!=1&&p->c!=-1)
{
cout<<p->c;
}
else if(p->c==-1)// 系数为-1,只输出-号
cout<<"-";
cout<<"X";
// 指数e不为1才输出
if(p->e!=1)
cout<<"^"<<p->e;
}
}
// 指向下一项
p=p->next;
}
// 如果系数全为0,输出一个0
if(flag==0)
cout<<0;
cout<<endl;
}
Node* PolyAdd(Node *h1,Node *h2)
{
Node *p1,*p2,*node;
if(h1->next==NULL)
{
return h2;
}
if(h2->next==NULL)
{
return h1;
}
p1=h1;
p2=h2->next;
while(p2!=NULL)
{
// 如果p1到最后一项了,则将p2剩余项拼接到p1后面
if(p1->next==NULL)
{
p1->next=p2;
break;
}
// 如果指数相等,则系数相加
if(p1->next->e==p2->e)
{
p1->next->c+=p2->c;
p1=p1->next;
p2=p2->next;
continue;
}
// 如果指数不相等,则将p2的项数插入p1
if((p2->e) > (p1->next->e))
{
node=new Node;
node->c=p2->c;
node->e=p2->e;
node->next=p1->next;
p1->next=node;
p2=p2->next;
}
p1=p1->next;
}
return h1;
}
int main()
{
Node *sum;
Node *h1=Create();
Node *h2=Create();
Print(h1);
Print(h2);
sum=PolyAdd(h1,h2);
Print(sum);
return 0;
}