《数据结构》线性结构——一元多项式的加法运算
题目
设计函数分别求两个一元多项式的和。
输入格式
每一次先输入多项式的非零项的个数,再按指数从大到小输入系数和指数,系数与指数中间有空格。
输出格式
输出合并后的多项式,若系数为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;
}