PAT 1009 Product of Polynomials (25 分)

PAT 1009 Product of Polynomials (25 分)

多项式链表的乘积

用链表L1的每一个节点和链表L2的每一个节点相乘之后进行加和,生成新的结果链表

具体代码

#include<iostream>
#include<malloc.h>
#include<iomanip>
using namespace std;

typedef struct node* Node;
struct node
{
	int exp;
	float cof;
	Node next;
};
typedef Node List;

List insert(List p, Node tmp)
{
	Node p1 = p;
	while ((p1->next)&&(p1->next->exp>tmp->exp))
	{
		p1 = p1->next;
	}
	if (p1->next == NULL)
	{
		p1->next = tmp;
		return p;
	}
	else
	{
		if (p1->next->exp == tmp->exp)
		{
			if (p1->next->cof + tmp->cof == 0)
			{
				Node t = p1->next;
				p1->next = t->next;
				free(t);
				free(tmp);
				return p;
			}
			else
			{
				p1->next->cof = p1->next->cof + tmp->cof;
				free(tmp);
				return p;
			}
		}
		else
		{
			tmp->next = p1->next;
			p1->next = tmp;
			return p;
		}
	}
}

List create()
{
	int n;
	cin >> n;//表明当前的节点数目
	List p = (List)malloc(sizeof(struct node));
	p->next = NULL;
	for (int i = 1; i <= n; i++)
	{
		Node tmp = (Node)malloc(sizeof(struct node));
		cin >> tmp->exp >> tmp->cof;
		tmp->next = NULL;
		p = insert(p, tmp);
	}
	return p;
}

List multiply(List L1, List L2)
{
	Node p1, p2;
	List L3 = (List)malloc(sizeof(struct node));
	L3->next = NULL;
	for (p1 = L1->next; p1; p1 = p1->next)
	{
		for (p2 = L2->next; p2; p2 = p2->next)
		{
			Node t = (Node)malloc(sizeof(struct node));
			t->exp = p1->exp + p2->exp;
			t->cof = p1->cof * p2->cof;
			t->next = NULL;
			insert(L3, t);
		}
	}
	return L3;
}

void print(List L)
{
	int count = 0;
	Node p1 = L->next;
	while (p1)
	{
		count++;
		p1 = p1->next;
	}
	Node p = L->next;
	cout.setf(ios::fixed);
	cout << count;
	while (p)
	{
		cout << " " << p->exp << " " << setprecision(1) << p->cof;
		p = p->next;
	}
}

int main()
{
	List L1 = create();
	//print(L1);
	List L2 = create();
	//print(L2);
	print(multiply(L1, L2));
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值