《数据结构》线性结构——一元多项式的加法运算

《数据结构》线性结构——一元多项式的加法运算

题目

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

输入格式

每一次先输入多项式的非零项的个数,再按指数从大到小输入系数和指数,系数与指数中间有空格。

输出格式

输出合并后的多项式,若系数为0则不输出

输入样例


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

输出样例

5x^20+10x^4-5x^2+9x^1

分析

使用链表,将合并前的多项式存在链表里,合并后的新多项式也存在链表里,系数与指数存在数据域里。

实现加法:
判断指数,相同的系数相加,否则指数大的直接作为新的结点

源码

#include<stdio.h>
#include<stdlib.h>
struct node
{
	int x;//系数
	int y;// 指数 
	struct node *next;
};

//获取链表 
struct node * get()
{
	int n;
	scanf("%d",&n);//记录输入的多项式个数;
	struct node *L=(struct node *)malloc(sizeof(struct node)); 
	struct node *head=L;
	while(n--)
	{
		struct node *t=(struct node *)malloc(sizeof(struct node)); 
	    int x,y;
	    scanf("%d%d",&x,&y);
	    t->x=x;
	    t->y=y;
	    L->next=t;
	    L=L->next;
	}
	printf("已完成!"); 
	L->next=NULL;
	return head->next;
}

//合并链表 
struct node *add(struct node *L1,struct node *L2)
{
	struct node *t1=L1;
	struct node *t2=L2;
	struct node *L=(struct node *)malloc(sizeof(struct node)); 
	struct node *head=L;
	while(t1&&t2)//直到有短链表已空 
	{
		struct node *t=(struct node *)malloc(sizeof(struct node)); 
		if(t1->y==t2->y)
		{
			t->y=t1->y;
			t->x=t1->x+t2->x;
			t1=t1->next;
			t2=t2->next;
		}
		else if(t1->y>t2->y)
		{
			t->x=t1->x;
			t->y=t1->y;
			t1=t1->next;
		}
		else 
		{
			t->x=t2->x;
			t->y=t2->y;
			t2=t2->next;
		}
		L->next=t;
		L=L->next;
	}
	if(t1) L->next=t1;
	if(t2) L->next=t2;//将长链表剩下的存到新链表里 
	printf("合并成功");
	L->next=NULL;
	return head->next;
}

//打印链表 
void PrintfLink(struct node *P)
{
	struct node *t=P;
	int flag=1;//做标记 
	for(;t;t=t->next)
	{
		if(t->x)
		{
			printf("%dx^%d",t->x,t->y);
			flag=0;
			}	
		if(t->next)
		{
			if(t->next->x>0) printf("+");.
		}
		       
	}
	if(flag) printf("0");
	printf("\n");
}

int main()
  {
    struct node *L1,*L2,*P;//构建链表,L为目标链表,P为相加后的链表
	L1=get();
	L2=get();//获取链表 
	P=add(L1,L2);//合并 
	PrintfLink(P); //打印输出 
  	system("pause");
  	return 0;
  	  }

拓展

多项式乘法

思路:将两链表循环相乘,单独一项×多项。但由于乘完后不是有序排列的,可以借助加法算法时的相加排序,每乘一项就合并进新链表,达到有序的目的。

乘法函数源码如下:

struct node * multiplication(struct node *L1,struct node *L2){
	struct node *tmpL1 = L1;
	struct node *tmpL2 = L2;
	struct node *mul=(List)malloc(sizeof(struct Node));
	mul->Next = NULL;
	struct node *head = mul;
	struct node *t;
	for(;tmpL1;tmpL1=tmpL1->Next)
		for(tmpL2 = L2;tmpL2;tmpL2=tmpL2->Next){
			t = (struct node *)malloc(sizeof(struct Node));
			t->x = tmpL1->x * tmpL2->x;  // 系数相乘
			t->z = tmpL1->z + tmpL2->z;  // 指数相加
			t->Next = NULL;
			head = add(t,mul);  // 将新增结点和之前已经排好序的结点排序 
			mul = head; // 重新确定开头 
		}
	return head;
}
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Isco也是O型腿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值