一元多项式的乘法与加法运算

#include<stdio.h>
#include<stdlib.h>

struct PolyNode{
	int c;
	int e;
	struct PolyNode *next;
};
typedef struct PolyNode *Node;

Node Read();
Node Mult(Node P1,Node P2);
Node Add(Node P1,Node P2);
void Print(Node P);
void Attach(int c,int e,Node *P);

int main()
{
	Node P1,P2;
	Node PM,PA;
	P1=Read();
	P2=Read();
	PM=Mult(P1,P2);
	PA=Add(P1,P2);
	Print(PM);
	Print(PA);
	return 0;
}

void Attach(int c,int e,Node *P)
{
	Node New;
	New=(Node)malloc(sizeof(struct PolyNode));
	New->c = c;
	New->e = e;
	New->next = NULL;
	(*P)->next = New;
	*P=New; 
}

Node Read()
{
	int num,c,e;
	scanf("%d",&num);
	Node P,rear,t;
	P=(Node)malloc(sizeof(struct PolyNode));
	P->next=NULL;
	rear=P;
	while(num--)
	{
		scanf("%d %d",&c,&e);
		Attach(c,e,&rear);
	}
	t=P;
	P=P->next;
	free(t);
	return P; 
}

Node Mult(Node P1,Node P2)
{
	Node P,rear;
	Node t1,t2,t;
	int c,e;
	t1=P1;
	t2=P2;
	P=(Node)malloc(sizeof(struct PolyNode));
	P->next = NULL;
	rear=P;
	if(!P1||!P2)
		return NULL;
	while(t2)
	{
		Attach(t1->c*t2->c ,t1->e+t2->e ,&rear);
		t2=t2->next;
	}
	
	while(t1)
	{
		rear=P;
		t2=P2;
		while(t2)
		{
			c=t1->c * t2->c;
			e=t1->e + t2->e;
			while(rear->e > e&&rear->e )
				rear=rear->next;
			if(rear->next->e == e&&rear->next)
			{
				if(rear->next->c+c)
					rear->next->c +=c;
				else
				{
					t=rear->next;
					rear->next = t->next;
					free(t);
				}
			}
			else
			{
				t=(Node)malloc(sizeof(struct PolyNode));
				t->c = c;
				t->e = e;
				t->next =rear->next;
				rear->next=t;
				rear=rear->next;
			}
			t2=t2->next;
		} 
		t1=t1->next;
	}
	t1=P;
	P=P->next;
	free(t1);
	return P;
}

Node Add(Node P1,Node P2)
{
	Node P,t1,t2,rear;
	int c,e;
	t1=P1;
	t2=P2;
	P=(Node)malloc(sizeof(struct PolyNode));
	P->next=NULL; 
	rear=P;
	while(t1&&t2)
	{
		if(t1->e > t2->e)
		{
			Attach(t1->c,t1->e,&rear);
			t1=t1->next;
		}		
		else if(t1->e == t2->e )
		{
			if(t1->c+t2->c)
			Attach(t1->c+t2->c,t1->e+t2->e,&rear);
			t1=t1->next;
			t2=t2->next;	
		}	
		else
		{ 
			Attach(t2->c,t2->e,&rear);
			t2=t2->next;
		} 
	}
	while(t1)
	{
		Attach(t1->c,t1->e,&rear);
		t1=t1->next;
	}
	while(t2)
	{
		Attach(t2->c,t2->e,&rear);
		t2=t2->next;
	}
	t1=P;
	P=P->next;
	free(t1);
	return P;
}

void Print(Node P)
{
	Node t;
	t=P;
	if(t)
	{
		while(t)
		{
			if(t!=P)
				printf(" ");
			printf("%d %d",t->c,t->e);
		}
		printf("\n");
	}
	else
		printf("0 0\n");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值