多项式相加单链表实现

#include<iostream>
using namespace std;

struct PolyNode{
	double coef;
	int exp;
	PolyNode *next;
};
class PolyClass
{
	PolyNode *head;//单链表的头结点指针
public:
	PolyClass();
	~PolyClass();
	void Disp();
	void CreateList(double a[],int b[],int n);
	void Sort();
	friend void PolyAdd(PolyClass &,PolyClass &,PolyClass &);
};
PolyClass::PolyClass()
{
	head=new PolyNode();
	head->next=NULL;
}
PolyClass::~PolyClass()
{
	PolyNode *pre,*p;
	pre=head,p=pre->next;
	while(p!=NULL)
	{
		delete pre;
		pre=p;
		p=p->next;
	}
	delete pre;
}
void PolyClass::CreateList(double a[],int b[],int n)
{
	int i;
	PolyNode *s,*r;
	r=head;
	for(i=0;i<n;i++)
	{
		s=new PolyNode();
		s->coef=a[i];s->exp=b[i];
		r->next=s;
		r=s;
	}
	r->next=NULL;
}
void PolyClass::Disp()
{
	bool flag=true;
	PolyNode *p;
	p=head->next;
	while(p!=NULL)
	{
		if(flag) flag=false;
		else if(p->coef>0)cout<<'+';
		if(p->exp==0)
			cout<<p->coef;
		else if(p->exp==1)
			cout<<p->coef<<'x';
		else 
			cout<<p->coef<<"x^"<<p->exp;
		p=p->next;
	}
	cout<<endl;
}
void PolyClass::Sort()//指数域递减排序
{
	PolyNode *p,*q,*pre;
	q=head->next;
	if(q==NULL)return;
	p=q->next;
	if(p==NULL)return;
	q->next=NULL;//构造只含有一个数据节点的单链表//重要
	while(p!=NULL)
	{
		q=p->next;//不断遍历下一个结点
		pre=head;//每次从头扫描
		while(pre->next!=NULL&&pre->next->exp>p->exp)
			pre=pre->next;//找到要插入的位置
		p->next=pre->next;
		pre->next=p;
		p=q;
	}
}
void PolyAdd(PolyClass &poly1,PolyClass &poly2,PolyClass &poly3)
{
	PolyNode *pa=poly1.head->next;
	PolyNode *pb=poly2.head->next;
	PolyNode *s,*r;
	r=poly3.head;
	double c;
	while(pa!=NULL&&pb!=NULL)
	{
		if(pa->exp<pb->exp)
		{
			s=new PolyNode();
			s->coef=pb->coef,s->exp=pb->exp;
			r->next=s;
			r=s;
			pb=pb->next;
		}
		else if(pa->exp>pb->exp)
		{
			s=new PolyNode();
			s->coef=pa->coef,s->exp=pa->exp;
			r->next=s;
			r=s;
			pa=pa->next;
		}
		else
		{
			c=pa->coef+pb->coef;
			if(c!=0)
			{
				s=new PolyNode();
			    s->coef=c,s->exp=pa->exp;
			    r->next=s;
			    r=s;
			}
			pa=pa->next,pb=pb->next;
		}
	}
	if(pb!=NULL)pa=pb;
	while(pa!=NULL)
	{
		s=new PolyNode();
		s->coef=pa->coef,s->exp=pa->exp;
		r->next=s;
		r=s;
		pa=pa->next;
	}
	r->next=NULL;
}

int main()
{
	PolyClass poly1,poly2,poly3;
	double a[20];int b[20],n;
	a[0]=2.0;b[0]=3;
	a[1]=3.2;b[1]=5;
	a[2]=-6.0;b[2]=1;
	a[3]=10.0;b[3]=0;n=4;
	poly1.CreateList(a,b,n);
	poly1.Sort();
	poly1.Disp();
	a[0]=6.0,b[0]=1;
	a[1]=1.8,b[1]=5;
	a[2]=-2.0,b[2]=3;
	a[3]=1.0,b[3]=2;
	a[4]=-2.5,b[4]=4;
	a[5]=-5.0,b[5]=0;n=6;
	poly2.CreateList(a,b,n);
	poly2.Sort();
	poly2.Disp();
	PolyAdd(poly1,poly2,poly3);
	poly3.Disp();
	return 0;
}




	
			

				






	


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值