PTA-数据结构-02-线性结构2 一元多项式的乘法与加法运算 (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 <stdio.h>
#include <stdlib.h>


typedef struct _Node
{
	int k;
	int e;
	struct _Node * next;
}Node;


typedef Node * List;

void printList(List l)
{	
	if (l->next == NULL)
	{
		printf("0 0");
	}
	else
	{
		while(l->next != NULL)
		{
			printf("%d %d", l->next->k, l->next->e);
			l = l->next;
			if (l ->next != NULL)
				printf(" ");
		}
	}
}

List newNode(int k, int e)
{
	List l = (List)malloc(sizeof(Node));
	l->k = k;
	l->e = e;
	l->next = NULL;
	
	return l;
}

void insertList(List l, int k, int e)
{
	while(l->next != NULL)
	{
		if (l->next->e == e)
		{
			l->next->k += k;
			
			// if the sum = 0, delete this item
			if (l->next->k == 0)
			{
				List temp = l->next;
				l->next = temp->next;
				free(temp);
				temp = NULL;
			}
			
			return;
		}
		else if (l->next->e < e)
		{
			List temp = newNode(k,e);
			temp->next = l->next;
			l->next = temp;
			return;
		}
		
		l = l->next; 
	}
	
	List temp = newNode(k,e);
	l->next = temp;
}


int main(void)
{
	List l1, l2, lp, ls, t;
	l1 = newNode(0,0);
	l2 = newNode(0,0);
	lp = newNode(0,0);
	ls = newNode(0,0);
	int n;
	
	// input first polynomial
	scanf("%d", &n);
	t = l1;
	for (int i=0;i<n;i++)
	{
		int k, e;
		scanf("%d %d", &k, &e);
		t->next = newNode(k, e);
		t = t->next;
	}
	
	// input second polynomial
	scanf("%d", &n);
	t = l2;
	for (int i=0;i<n;i++)
	{
		int k, e;
		scanf("%d %d", &k, &e);
		t->next = newNode(k, e);
		t = t->next;
	}
	
	// calculate the product
	List l1Temp = l1;
	List l2Temp = l2; 
	while(l1->next != NULL)
	{
		l2 = l2Temp;
		while(l2->next != NULL)
		{
			int e = l1->next->e + l2->next->e;
			int k = l1->next->k * l2->next->k;
			insertList(lp, k ,e);
			
			l2 = l2->next;
		}
		
		l1 = l1->next;
	}
	printList(lp);
	printf("\n");
	
	
	// calculate the sum
	l1 = l1Temp;
	l2 = l2Temp;
	while(l1->next != NULL)
	{
		int e = l1->next->e;
		int k = l1->next->k;
		insertList(ls, k ,e);
		
		l1 = l1->next;
	}
	
	while(l2->next != NULL)
	{
		int e = l2->next->e;
		int k = l2->next->k;
		insertList(ls, k ,e);
		l2 = l2->next;
	}
	printList(ls);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值