7-2 一元多项式的乘法与加法运算 (50分)
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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
这道题目说难也不难,说简单的话还是要花点时间的,算是一道中等题目吧。这里面主要就是需要利用结构化思想,将问题进行拆分,从大体上看,可以拆分成乘法和加法俩个步骤,然后,乘法实际上又可以看作循环的加法,加法的话还是比较好实现的,就是利用俩条链表的原有空间,重新链接成一条新的链表,
重点是如何实现乘法,例如(Ax+B)*(Ax^ 2+2)就可以拆分成(Ax+B)*Ax^2+(Ax+B)*2。因此我们就可以分成三个步骤,首先,对链表2进行遍历,依次取出他们节点的数据,第二,每取出一个节点数据,就重新生成一条与链表1一样的链表(这就需要再定义一个copy函数),并依次乘上这个节点的数据,第三,利用已经写好的加法函数将得到的新链表加到之前得到的新链表上面。不断循环,直到链表2被遍历完。
代码如下
#include<bits/stdc++.h>
using namespace std;
struct Node
//节点 ,用来存储系数和指数以及搭建链表
{
int coef;
int expn;
Node *next;
};
void print(Node *head)
//输出链表
{
Node *p=head->next;
if(p)
{
while(p->next!=NULL)
{
cout<<p->coef<<" "<<p->expn<<" ";
p=p->next;
}
cout<<p->coef<<" "<<p->expn;
}
else
{
cout<<"0 0";
}
}
void add(Node *head1,Node *head2)
//加法,将head1与head2相加,结果存到head1中
{
Node *p1=head1->next;
Node *p2=head2->next;
Node *p_prior=head1,*p;
while(p1&&p2)//三种情况
{
if(p1->expn>p2->expn)
{
p_prior->next=p1;
p1=p1->next;
p_prior=p_prior->next;
}
else if(p1->expn<p2->expn)
{
p_prior->next=p2;
p2=p2->next;
p_prior=p_prior->next;
}
else
{
int x=p1->coef+p2->coef;
if(x==0)
{
p=p1;
p1=p1->next;
free(p);
p=p2;
p2=p2->next;
free(p);
}
else
{
p1->coef=p1->coef+p2->coef;
p_prior->next=p1;
p=p2;
p2=p2->next;
free(p);
}
}
}
p_prior->next=p1?p1:p2;
free(head2);
}
Node* copy(Node *head1)
//复制head1指向的整条链表, 返回复制链表的头结点
{
Node *head,*p=head1,*tail,*p1;
head=new Node;
tail=head;
p=p->next;
while(p)
{
p1=new Node;
p1->coef=p->coef;
p1->expn=p->expn;
p1->next=NULL;
tail->next=p1;
tail=tail->next;
p=p->next;
}
return head;
}
Node* mul_all(Node *head1,Node *head2)
//俩条链表相乘,返回相乘后链表的头结点
{
Node *p,*answer;
answer=new Node;
answer->next=NULL;
Node *p2=head2->next;
while(p2)
{
Node *p_head=copy(head1);
p=p_head->next;
while(p)
{
p->coef=p2->coef*p->coef;
p->expn=p->expn+p2->expn;
p=p->next;
}
add(answer,p_head);
p2=p2->next;
}
return answer;
}
int main()
{
int k1,k2,a,b,i=0;
Node *head1,*head2,*head3,*p1,*p,*p2;
head1=new Node;
head2=new Node;
p1=head1;
p2=head2;
cin>>k1;
while(i<k1) //链表1
{
cin>>a>>b;
i++;
p=new Node;
p->coef=a;
p->expn=b;
p->next=NULL;
p1->next=p;
p1=p;
}
cin>>k2;
i=0;
while(i<k2) //链表2
{
cin>>a>>b;
i++;
p=new Node;
p->coef=a;
p->expn=b;
p->next=NULL;
p2->next=p;
p2=p;
}
head3=mul_all(head1,head2);
print(head3);
cout<<endl;
add(head1,head2);
print(head1);
}
如果觉得有帮助,可以关注一下我的公众号,我的公众号主要是将这些文章进行美化加工,以更加精美的方式展现出来,同时记录我大学四年的生活,谢谢你们!