表达式求解

//数据结构 实验一
#include
using namespace std;

struct unit
{
	float coef;  // 系数
	int expn;    // 指数
};
typedef struct polynomial
{
	unit e;
	polynomial *next;
	polynomial *head;
}*P;

int cmp(unit a,unit b);
void CreatePolyn(P &p,int m);
void print(P &ha);
void AddPolyn(P &Pa,P &Pb);

int main()
{
	P Pa,Pb;
	int m;
	cout<<"输入表达式Pa的项数:"<<endl;
	cin>>m;
	cout<<"输入表达式Pa的各项(按指数的从大到小的顺序):"<<endl;
	CreatePolyn(Pa,m);
	cout<<"输入表达式Pb的项数:"<<endl;
	cin>>m;
	cout<<"输入表达式Pb的各项(按指数的从大到小的顺序):"<<endl;
	CreatePolyn(Pb,m);
	AddPolyn(Pa,Pb);
	cout<<"结果如下:"<<endl;
	print(Pa);
}
int cmp(unit a,unit b)
{
	if(a.expn > b.expn)
		return -1;
	else if(a.expn == b.expn)
		return 0;
	else if(a.expn < b.expn)
		return 1;
}
void CreatePolyn(P &p,int m)
{
	p = new polynomial;
	p->next = NULL;
	p->head = p;
	p->e.coef = 0.0;
	p->e.expn = -1;
	int i;
	P now;
	for (i = 1;i <= m;i++)
	{
		float coef;
		int expn;
		cin>>coef>>expn;
		P s;
		s = new polynomial;
		s->e.coef = coef;
		s->e.expn = expn;
		if(i==1)
		{
			s->next= p->next;
			p->next= s;
		}
		else
		{
			s->next= now->next;
			now->next = s;
		}
		s->head = p;
		now = s;
		
	}
}
void print(P &ha)
{
	for(P i =ha->head->next;i;i = i->next)
	{
		if(!i->next)
		{
			cout<<i->e.coef<<""<<i->e.expn<<endl;
			break;
		}
		cout<<i->e.coef<<""<<i->e.expn<<",";
	}
}
void AddPolyn(P &Pa,P &Pb)
{
	P ha,hb,qa,qb;
	unit a,b;
	ha = Pa->head;
	hb = Pb->head;
	qa = Pa->next;
	qb = Pb->next;
	while(qa && qb)
	{
		float sum;
		a = qa->e;
		b = qb->e;
		switch(cmp(a,b))
		{
		case -1:   //a > b
			ha = qa;
			qa = qa->next;
			break;
		case 0:
			sum = a.coef + b.coef;
			if(sum != 0.0)
			{
				qa->e.coef = sum;
				ha = qa;
			}
			else
			{
				//删除PA中当前结点
				ha->next = qa->next;
				//释放空间
				delete qa;
			}
			hb->next = qb->next;
			delete qb;
			
			qb = hb->next;
			qa = ha->next;
			break;
		case 1:
			hb->next = qb->next;
			
			qb->next = ha->next;
			ha->next = qb;
			
			qb = hb->next;
			ha = ha->next;
			break;
		}
	}
	if(Pb->head->next)
		ha->next = qb;//链接剩余节点
	delete hb;
}

你可能感兴趣的:(表达式求解)