顺序表存储一元多项式,并实现两个多项式相加运算(C++,无序输入)

         采用顺序表存储一元多项式,并实现两个多项式相加运算,要求:

1)创建存储多项式的有序表(按无序输入)hahb

2)求hahb相加产生多项式hc

3)输出多项式hahbhc

#include
#include
using namespace std;
typedef struct node
{
	int coef;//系数
	int expn;//指数
}Elem;
typedef struct node1
{
	Elem* base;
	int length;
}Ss;
bool cmp1(node a, node b)
{
	return a.expn < b.expn;//指数大的往后
}
void Init(Ss& s)//初始化
{
	s.base = new Elem[1000];
	s.length = 0;
}
void Create(Ss& s)//创建多项式
{
	cout << "输入项数:";
	cin >> s.length;
	cout << "先输指数再输系数:" << endl;
	for (int i = 0; i < s.length; i++)
		cin >> s.base[i].expn >> s.base[i].coef;
	sort(s.base, s.base + s.length, cmp1);//根据指数升序排序
}
void Add(Ss& ha, Ss& hb, Ss& hc)//合并多项式
{
	int i = 0, j = 0, k = 0;
	while (ha.length && hb.length)
	{
		hc.length++;
		if (ha.base[i].expn == hb.base[j].expn)//指数相等
		{
			ha.length--, hb.length--;
			int sum = ha.base[i].coef + hb.base[j].coef;
			if (sum == 0)
				continue;
			else
			{
				hc.base[k].coef = sum;
				hc.base[k++].expn = ha.base[i].expn;
			}
			i++, j++;
		}
		else if (ha.base[i].expn < hb.base[j].expn)//ha指数小于hb指数
		{
			ha.length--;
			hc.base[k].coef = ha.base[i].coef;
			hc.base[k++].expn = ha.base[i].expn;
			i++;
		}
		else//hb指数小于ha指数
		{
			hb.length--;
			hc.base[k].coef = hb.base[j].coef;
			hc.base[k++].expn = hb.base[j].expn;
			j++;
		}
	}
	if (ha.length == 0)//ha连完 剩下连hb
	{
		for (int d = j; d < hb.length; d++)
		{
			hc.base[k].coef = hb.base[d].coef;
			hc.base[k++].expn = hb.base[d].expn;
		}
	}
	else if (hb.length == 0)//hb连完 剩下连ha
	{
		for (int d = j; d < ha.length; d++)
		{
			hc.base[k].coef = ha.base[d].coef;
			hc.base[k++].expn = ha.base[d].expn;
		}
	}
}
void Print(Ss s)//输出多项式
{
	int i;
	cout << "f=";
	for (i = 0; i < s.length - 1; i++)
	{
		if (s.base[i].expn == 0)
			cout << s.base[i].coef << " + ";
		else
			cout << s.base[i].coef << "x^" << s.base[i].expn << " + ";
	}
	cout << s.base[i].coef << "x^" << s.base[i].expn;
	cout << endl;
}
int main()
{
	Ss ha, hb, hc;
	Init(ha);
	Create(ha);
	Init(hb);
	Create(hb);
	cout << "多项式1:" << endl;
	Print(ha);
	cout << "多项式2:" << endl;
	Print(hb);
	Init(hc);
	Add(ha, hb, hc);
	cout << "合并多项式:" << endl;
	Print(hc);
}

顺序表存储一元多项式,并实现两个多项式相加运算(C++,无序输入)_第1张图片

你可能感兴趣的:(算法,c++,图论)