1002. A+B for 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 CreatList()
{
	List L=new struct Node;
	L->Next = NULL;
	List rear = L;
	int N;
	double coef;
	int expon;
	cin >> N;
	cin.get();
	while (N--)
	{
		cin >> expon;
		cin.get();
		cin >> coef;
		cin.get();
		Attach(expon, coef,&rear);
	}
	List tmp = L;
	L = L->Next;
	delete tmp;
	return L;
}
int Compare(int a, int b)
{
	if (a > b)return 1;
	if (a < b)return -1;
	if (a == b)return 0;
}
List Add(List L1, List L2)
{
	List p1, p2;
	List L = new struct Node;
	L->Next = NULL;
	List rear = L;
	p1 = L1, p2 = L2;
	while (p1&&p2)
	{
		switch (Compare(p1->expon, p2->expon))
		{
		case 1:
			Attach(p1->expon, p1->coef, &rear);
			p1 = p1->Next;
			break;
		case -1:
			Attach(p2->expon, p2->coef, &rear);
			p2 = p2->Next;
			break;
		case 0:
			if (p1->coef + p2->coef == 0);
			else
				Attach(p1->expon, p1->coef + p2->coef, &rear);
			p1 = p1->Next;
			p2 = p2->Next;
			break;
		}
	}
	while (p1)
	{
		Attach(p1->expon, p1->coef, &rear);
		p1 = p1->Next;
	}
	while (p2)
	{
		Attach(p2->expon, p2->coef, &rear);
		p2 = p2->Next;
	}
	List tmp = L;
	L = L->Next;
	delete tmp;
	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 = CreatList();
	List L2 = CreatList();
	List L = Add(L1, L2);
	Print(L);
	return 0;
}
精度设置:头文件include<iomanip>,小数点后一位设置setiosflags(ios::fixed)<<setprecision(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值