1009. Product of Polynomials (25)

#include<iostream>
#include<iomanip>
using namespace std;
typedef struct Node * List;
struct Node {
	int expon;
	double coef;
	List Next;
};
void Attach(int expon, double coef, List * Rear)
{
	List tmp = new struct Node;
	tmp->coef = coef;
	tmp->expon = expon;
	tmp->Next = NULL;
	(*Rear)->Next = tmp;
	*Rear = tmp;
}
List ReadList()
{
	List L = new struct Node;
	L->Next = NULL;
	List rear = L;
	int N;
	cin >> N;
	double coef;
	int expon;
	while (N--)
	{
		cin >> expon;
		cin >> coef;
		Attach(expon, coef, &rear);
	}
	L = L->Next;
	return L;
}
void Insert(List L, int expon, double coef)		//L头结点是空的,这种用p->Next很方便
{
	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)
		{
			List tmp = p->Next;
			p->Next = tmp->Next;
			delete tmp;
		}
		else
			p->Next->coef += coef;
	}
	else			//到了最后一个节点后的空节点或者加在两个节点中间
	{
		List tmp = new struct Node;
		tmp->coef = coef;
		tmp->expon = expon;
		tmp->Next = p->Next;
		p->Next = tmp;
	}
}
List Mult(List L1, List L2)
{
	if (!L1 || !L2)return NULL;
	List p1 = L1, p2 = L2;
	List L = new struct Node;
	L->Next = NULL;
	List rear = L;
	double coef;
	int expon;
	while (p2)
	{
		expon = p1->expon + p2->expon;
		coef = p1->coef*p2->coef;
		Attach(expon, coef, &rear);
		p2 = p2->Next;
	}
	p1 = L1->Next;
	p2 = L2;
	while (p1)
	{
		p2 = L2;
		while (p2)
		{
			expon = p1->expon + p2->expon;
			coef = p1->coef*p2->coef;
			Insert(L, expon, coef);
			p2 = p2->Next;
		}
		p1 = p1->Next;
	}
	L = L->Next;
	return L;
}
void Print(List L)
{
	List p = L;
	int count = 0;
	while (p)
	{
		count++;
		p = p->Next;
	}
	cout << count;
	p = L;
	while (p)
	{
		cout <<" "<< p->expon << " " << setiosflags(ios::fixed) << setprecision(1) << p->coef;
		p = p->Next;
	}
}
int main()
{
	List L1 = ReadList();
	List L2 = ReadList();
	List L = Mult(L1, L2);
	Print(L);
	return 0;
}
/*2 1 2.4 0 3.2 2 2 1.5 1 0.5*/

Insert函数中每次插进一个新元素都要从头开始扫描

陈越老师讲的那个方法很巧妙,每次进来的指数肯定在Rear或者Rear后面,前面的就不用扫描,直接插在后面就可以

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值