数据结构-------一元多项式运算

两个一元多项式相加。

比如输入

x+x2+x4

x+2x2+x3

之后的结果为

2x+3x2+x3+x^4

输入输出样例:1组
#1

样例输入:

//输入第一个多项式,按照系数、指数的形式输入每一个子项!
1 1 
1 2 
1 4 
0 0 //输入结束的条件,系数和指数同时为0时输入结束
1 1 
2 2 
1 3 
0 0 

样例输出:

2 1 
3 2 
1 3 
1 4 
//注意
    //1:该程序每次运行的时间必须小于10秒,否则会超时,程序超时将不会测试剩余的测试集
    //2:该程序每次运行使用的内存不能超过1M,否则会返回错误
    //3:该程序每次运行输出的结果最多显示1000个字符(多余的不显示),每行末尾的所有空格用□表示
#include<iostream>

using namespace std;

typedef struct node
{
	int exp;
	int coef;
	struct node *next;
}ListNode;

ListNode *createpoly();
ListNode *addpoly(ListNode *h1,ListNode *h2);
void disppoly(ListNode *h);
int main()
{
	ListNode *head1,*head2,*head;
	//cout<<"创建第一个多项式:";
	head1=createpoly();
	//cout<<"创建第二个多项式:";
	head2=createpoly();
	//cout<<"将两个多项式相加:;
	head=addpoly(head1,head2);
	disppoly(head);
}
ListNode *createpoly() //创建多项式链表
{
  ListNode *h=NULL,*p,*q=NULL;
  int e;
  int c;
  //cout<<"请输入系数和指数:";
  cin>>c>>e;
  while(e!=0||c!=0)
  {
  	p=new ListNode;
  	p->coef=c;
  	p->exp=e;
  	p->next=NULL;
  	if(h==NULL)
  	h=p;
  	else
  	q->next=p;
  	q=p;
  	//cout<<"请输入系数和指数:";
  	cin>>c>>e;
   }
	  return h;
}
 /*将两个多项式相加*/
 ListNode *addpoly(ListNode *h1,ListNode *h2)
 {
 	ListNode *p,*r=NULL,*s1,*s2,*s=NULL;
 	int c;
 	int e;
 	s1=h1;
 	s2=h2;
 	while(s1!=NULL&&s2!=NULL)
 	{
 		if(s1->exp==s2->exp)
 		{
 			c=s1->coef+s2->coef;
 			e=s1->exp;
 			s1=s1->next;
 			s2=s2->next;
		 }
		 else if(s1->exp<s2->exp)
		 {
		 	c=s1->coef;
		 	e=s1->exp;
		 	s1=s1->next;
		 }
		 else
		 {c=s2->coef;
		 e=s2->exp;
		 s2=s2->next;
		 }
		 if(c!=0)
		 {
		 	p=new ListNode;
		 	p->coef=c;
		 	p->exp=e;
		 	p->next=NULL;
		 	if(s==NULL)
		 	s=p;
		 	else
		 	r->next=p;
		 	r=p;
		 }
	 }
	 while(s1!=NULL)
	 {
	 	c=s1->coef;
	 	e=s1->exp;
	 	s1=s1->next;
	 	if(c!=0)
	 	{
	 		p=new ListNode;
		 	p->coef=c;
		 	p->exp=e;p->next=NULL;
		 	if(s==NULL)
		 	s=p;
		 	else
		 	r->next=p;
		 	r=p;
		 }
	 }
	 while(s2!=NULL)
	 {
	 	c=s2->coef;
	 	e=s2->exp;
	 	s2=s2->next;
	 	if(c!=0)
	 	{
	 		p=new ListNode;
		 	p->coef=c;
		 	p->exp=e;p->next=NULL;
		 	if(s==NULL)
		 	s=p;
		 	else
		 	r->next=p;
		 	r=p;
		 }
	 }
	 return s;
  }
/*输出多项式*/
void disppoly(ListNode *h)
{
	ListNode *p;
	p=h;
	while(p!=NULL)
	{
		if(p->exp==0)
		cout<<p->coef;
		else
		cout<<p->coef<<" "<<p->exp<<" "<<endl;
		p=p->next;
	}
 }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值