7-2 一元多项式的乘法与加法运算(20 分)

#include
using namespace std;
typedef struct LNode * List;
struct LNode {
	int coef;
	int expon;
	List Next;
};
void Attach(List L, int coef, int expon)
{
	if (!L)
	{
		L->coef = coef;
		L->expon = expon;
		L->Next = NULL;
	}
	else
	{
		List p = L;
		while (p->Next)
			p = p->Next;
		List tmp = new struct LNode;
		tmp->coef = coef;
		tmp->expon = expon;
		p->Next = tmp;
		tmp->Next = NULL;
	}
}
List Read()
{
	List L = new struct LNode;
	L->Next = NULL;
	int N;
	int coef, expon;
	cin >> N;
	cin.get();
	while (N--)
	{
		cin >> coef;
		cin.get();
		cin >> expon;
		cin.get();
		Attach(L, coef, expon);
	}
	List p = L;
	L = L->Next;
	delete p;
	return L;
}

List Add(List L1, List L2)
{
	List L = new struct LNode;
	L->Next = NULL;
	if (!L1)return L2;
	else if (!L2)return L1;
	else if (!L1 || !L2)return NULL;
	List p1, p2;
	p1 = L1;
	p2 = L2;
	while (p1&&p2)
	{
		if (p1->expon > p2->expon)
		{
			Attach(L, p1->coef, p1->expon);
			p1 = p1->Next;
		}
		else if (p1->expon < p2->expon)
		{
			Attach(L, p2->coef, p2->expon);
			p2 = p2->Next;
		}
		else
		{
			if (p1->coef + p2->coef != 0)
				Attach(L, p1->coef + p2->coef, p1->expon);
			p1 = p1->Next;
			p2 = p2->Next;
		}
	}
	while (p1) {
		Attach(L, p1->coef, p1->expon);
		p1 = p1->Next;
	}
	while (p2) {
		Attach(L, p2->coef, p2->expon);
		p2 = p2->Next;
	}
	List tmp;
	tmp = L;
	L = L->Next;
	delete tmp;
	return L;
}
void Insert(List L, int coef, int expon)
{
	List p = L;
	while (p->Next&&p->Next->expon > expon)
		p = p->Next;
	if (p->Next&&p->Next->expon == expon)
	{
		if (p->Next->coef + coef != 0)
			p->Next->coef += coef;
		else
		{
			List tmp = p->Next;
			p->Next = tmp->Next;
			delete tmp;
		}
	}
	else
	{
		List tmp = new struct LNode;
		tmp->coef = coef;
		tmp->expon = expon;
		tmp->Next = p->Next;
		p->Next = tmp;
	}
	
}
List Mult(List L1, List L2)
{
	List L = new struct LNode;
	L->Next = NULL;
	List p1, p2;
	p1 = L1, p2 = L2;
	int coef, expon;
	if (!L1 || !L2)
		return NULL;
	if (p1)
	{
		while (p2)
		{
			coef = p1->coef*p2->coef;
			expon = p1->expon + p2->expon;
			Attach(L, coef, expon);
			p2 = p2->Next;
		}
	}
	p1 = L1->Next;
	p2 = L2;	//重新赋值,p2已经为空
	while (p1)
	{
		List p = L;
		p2 = L2;		//	这里记得重新赋值,之前就是这里有问题
		while (p2)
		{
			coef = p1->coef*p2->coef;
			expon = p1->expon + p2->expon;
			Insert(L, coef, expon);
			p2 = p2->Next;
		}
		p1 = p1->Next;
	}
	List tmp;
	tmp = L;
	L = L->Next;
	delete tmp;
	return L;
}
void Print(List L)
{
	if (!L)
	{
		cout << 0 << " " << 0;
		return;
	}
	if (L)
	{
		cout << L->coef << " " << L->expon;
	}
	List p = L->Next;
	while (p)
	{
		cout << " " << p->coef << " " << p->expon;
		p = p->Next;
	}
}
int main()
{
	List L1 = Read();
	List L2 = Read();
	List A = Add(L1, L2);
	List M = Mult(L1, L2);
	Print(M);
	cout << endl;
	Print(A);
	cin.get();
	return 0;
}

思路是陈越老师课上讲的那个,这个是我自己写得,细节方面有些粗糙,仅供参考

运行截图

 

你可能感兴趣的:(数据结构)