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

设计函数分别求两个一元多项式的乘积与和。

输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。

输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。

输入样例:

4 3 4 -5 2  6 1  -2 0
3 5 20  -7 4  3 1

输出样例:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0

代码部分:

#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
typedef struct LNode* List;
struct LNode {
	int coef;
	int expon;
	List Next;
};
List CreatList();
void attach(int coef,int expon,List *pRear);
List Add(List L1, List L2);
List Multiply(List L1, List L2);
void print(List L);
int main() {
	List L1, L2, L1_rear, L2_rear;
	L1 = CreatList();
	L2 = CreatList();
	List AddL=Add(L1, L2);
	List MulL=Multiply(L1, L2);
	print(MulL);
	print(AddL);
	return 0;
}
List CreatList() {
	List head, p, temp;
	int n, coef, expon;
	head = (List)malloc(sizeof(struct LNode));
	p = head;
	scanf("%d", &n);
	for (int i = 0;i < n;i++) {
		scanf("%d%d", &coef, &expon);
		temp = (List)malloc(sizeof(struct LNode));
		temp->coef = coef;
		temp->expon = expon;
		temp->Next = NULL;
		p->Next = temp;
		p = temp;
	}
	temp = head;
	head = head->Next;
	free(temp);
	return head;
}
void attach(int coef, int expon, List* pRear) {
	List NewNode = (List)malloc(sizeof(struct LNode));
	NewNode->coef = coef;
	NewNode->expon = expon;
	NewNode->Next = NULL;
	(*pRear)->Next = NewNode;
	(*pRear) = NewNode;
}
List Add(List L1, List L2) {
	List head, p, r, p1, p2;
	head = (List)malloc(sizeof(struct LNode));
	r = p = head;
	p1 = L1;
	p2 = L2;
	while (p1 && p2) {
		if (p1->expon > p2->expon) {
			attach(p1->coef, p1->expon, &r);
			p1 = p1->Next;
		}
		else if (p1->expon < p2->expon) {
			attach(p2->coef, p2->expon, &r);
			p2 = p2->Next;
		}
		else {
			int sum = p1->coef + p2->coef;
			if(sum)
				attach(p1->coef + p2->coef, p1->expon, &r);
			p1 = p1->Next;
			p2 = p2->Next;
		}
	}
	for (;p1; p1 = p1->Next)attach(p1->coef, p1->expon, &r);
	for (;p2; p2 = p2->Next)attach(p2->coef, p2->expon, &r);
	head = head->Next;
	free(p);
	return head;
}
List Multiply(List L1, List L2) {
	List head, r, p1, p2;
	head = NULL;
	p1 = L1;
	p2 = L2;
	while (p1) {
		List temp = (List)malloc(sizeof(struct LNode));
		r = temp;
		int c, e;
		p2 = L2;
		while (p2) {
			c = p1->coef * p2->coef;
			e = p1->expon + p2->expon;
			attach(c, e, &r);
			p2 = p2->Next;
		}
		temp = temp->Next;
		head = Add(head, temp);
		p1 = p1->Next;
	}
	return head;
}
void print(List L) {
	if (L == NULL)
		printf("0 0\n");
	else {
		while (L->Next) {
			printf("%d %d ", L->coef, L->expon);
			L = L->Next;
		}
		printf("%d %d\n", L->coef, L->expon);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值