一元多项式的相加

 

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 127  Solved: 43
[Submit][Status][Web Board]

Description

一条单链表可以表示一个一元多项式,每个节点包含三个域:指数、系数和后继节点(指针或引用)。

表示多项式3X4-6X2+5X-10的单链表如图所示。给定两个多项式,实现两个多项式相加算法。

 

Input

第一行输入包含两个整数m,n

后续为m行和n行数据

m,n分别代表两个多项式的项数

后续每一行代表多项式的项,包含a,b两个数据,表示该项的系数和指数。

 

Output

从较高指数到较低指数,依次输出求得的和。

每行一项,格式与输入相同,但无需输出项数,系数为0的项也不输出。

Sample Input

2  3

1  2

1  1

2  2

1  1

2  0

Sample Output

3  2

2  1

2  0

#include<cstdio>
#include<malloc.h>
#include<iostream>
using namespace std;
typedef struct polynomial//定义多项式的结构体 
{
	int constant;      //系数项 
	int index;         //指数项 
	struct polynomial * next;
}poly,*list;
list creatList(int n)//n为多项式的项数 
{
	int i;
	list head,tail,s;
	head=(list)malloc(sizeof(poly));
	head->next=NULL;
	tail=head;
	for(i=0;i<n;i++)    //依次输入多项式的每一项 
	{
		s=(list)malloc(sizeof(poly));
		cin>>s->constant>>s->index;
		s->next=NULL;
		tail->next=s;
		tail=s;
	}
	return head;  //返回head指针 
	
}

list addTwoList(list l1,list l2)
{
	list l3,s;
	list p1,p2,p3;
	l3=(list)malloc(sizeof(poly));
	l3->next=NULL;
	p1=l1->next;
	p2=l2->next;
	p3=l3;      //p1,p2代表要相加的两个多项式,p3作为相加后新的多项式 
	while(p1&&p2)//判断两个多项式的指数是否相同 
	{
		if(p1->index>p2->index)
		{
			s=p1->next;
			p3->next=p1;
			p3=p1;
			p3->next=NULL;
			p1=s;
		}
		else  if(p1->index==p2->index)
			  {
				p1->constant+=p2->constant;//把p1或者p2作为相加后的新节点连接到p3上面 
				if(p1->constant!=0)
				{
					p3->next=p1;
					s=p1->next;
					p3=p1;
					p3->next=NULL;
					p1=s;
					p2=p2->next;
				}
				else
				{
					p1=p1->next;
					p2=p2->next;
				}
			  }
			  else
			  {
			  	s=p2->next;
			  	p3->next=p2;
			  	p3=p2;
			  	p3->next=NULL;
			  	p2=s;
			  }
	}
	if(p1!=NULL)
	    p3->next=p1;
	if(p2!=NULL) 
	     p3->next=p2;
	return l3;
	
}

void visitList(list l)
{
	list p;
	p=l->next;
	while(p!=NULL)
	{
		printf("%d %d\n",p->constant,p->index);
		p=p->next;
	}
}
int main()
{
	int a,b;
	list L1,L2,L3;
	scanf("%d%d",&a,&b);//a,b代表两个多项式各有多少项 
	L1=creatList(a);
	L2=creatList(b);
	L3=addTwoList(L1,L2);
	visitList(L3);
	return 0;
	
} 

 

转载于:https://my.oschina.net/shydream/blog/717931

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值