您的位置:首页 > 其它

一元多项式的表示及相加

2014-10-15 16:32 447 查看
#include <iostream>
using namespace std;

struct polynode
{
	double coef;
	int exp;
	struct polynode *next;
};

struct polynode *CreatNode();
struct polynode *AddNode(struct polynode *p,struct polynode *q);
void DisplayNode(struct polynode *head);

int main()
{
	cout<<"P(x):"<<endl;
	struct polynode *p1;
	p1=CreatNode();
	cout<<"P(x)=";
	DisplayNode(p1);
	cout<<endl;
	cout<<"Q(x):"<<endl;
	struct polynode *p2;
	p2=CreatNode();
	cout<<"Q(x)=";
	DisplayNode(p2);
	
	cout<<"P(x)+Q(x)=";
	polynode *p3;
	p3=AddNode(p1,p2);
	DisplayNode(p3);
	return 0;
}

struct polynode *CreatNode()
{
	polynode *head;
	polynode *p,*q;
	int coef,exp;
	head = new struct polynode;
	head->next=NULL;
	cin>>coef>>exp;
	while(coef!=0 || exp!=0) //输入并检测(若输入00)结束
	{
		p=new struct polynode;		//生成新结点
		p->coef=coef;		//装入数据
		p->exp=exp;
		q=head;
		while(q->next!=NULL)
		{
			q=q->next;
		}		 
		q->next = p;   //插到最后一个结点后
		p->next = NULL;//初始化p节点 
		cin>>coef>>exp;//循环输入新节点 
	}
	return  head;	
} 

void DisplayNode(struct polynode *head)
{
	if(head==NULL)
	{
		cout<<"Not Exist!\n"<<endl;
		return ;
	}
	struct polynode *p;
	p=head->next;
	while(p!=NULL)
	{
		if(p->coef>=0)
			cout<<p->coef<<"x^"<<p->exp;//正系数 
		else
			cout<<"("<<p->coef<<")"<<"x^"<<p->exp;//负系数 
		if(p->next!=NULL)
			cout<<"+";
		p=p->next;
	}
	cout<<endl;
}

struct polynode *AddNode(struct polynode *p,struct polynode *q)
{
	struct polynode *r = new struct polynode;
	r->next = NULL;
	polynode *p1 = p->next;
	polynode *p2 = q->next;
	polynode *p3;
	polynode *rear = r;
	
	while(p1!=NULL && p2!=NULL)
	{
		if(p1->exp < p2->exp)
		{
			p3=new polynode;
			p3->coef=p2->coef;
		    p3->exp=p2->exp;
			p3->next=NULL;
			rear->next=p3;
			rear=p3;
			p2=p2->next;
		}
		else if (p1->exp > p2->exp)
		{
			p3=new polynode;
			p3->coef=p1->coef;
			p3->exp=p1->exp;
			p3->next=NULL;
			rear->next=p3;
			rear=p3;
			p1=p1->next;
		}
		else //p1->exp == p2->exp
		{
			if((p1->coef + p2->coef) != 0)
			{
				p3=new polynode;
				p3->coef = p1->coef + p2->coef;
				p3->exp= p1->exp;
				p3->next=NULL;
				rear->next=p3;
				rear=p3;
			}
			p1=p1->next;
			p2=p2->next;
		}
	}
	if(p1==NULL)//若p1全部遍历 
	{
		while(p2!=NULL)
		{
			p3=new polynode;
			p3->coef=p2->coef;
			p3->exp=p2->exp;
			p3->next=NULL;
			rear->next=p3;
			rear=p3;
			p2=p2->next;
		}
	}
	else //p2==NULL,
	{
		while(p1!=NULL)
		{
			p3=new polynode;
			p3->coef=p1->coef;
			p3->exp=p1->exp;
			p3->next=NULL;
			rear->next=p3;
			rear=p3;
			p1=p1->next;
		}
	}
	return r;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: