一元多项式的乘法与加法运算
题目
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
typedef int ElementType;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
struct Node {
//系数
ElementType coef;
//次数
ElementType expon;
PtrToNode link;
};
List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表;空链表将输出NULL */
List Mult( List L1, List L2 );
List Add( List L1,List L2);
void Attach(ElementType a,ElementType b,PtrToNode *Rear);
int main(){
List L1, L2, L;
L1 = Read();
L2 = Read();
L = Mult(L1, L2);
Print(L);
L = Add(L1,L2);
Print(L);
return 0;
}
List Read(){
int num = -1;
cin>>num;
if(num == 0 && num == -1){
return NULL;
}
List L = new Node;
L->link = NULL;
//让尾部指针指向空节点
PtrToNode Rear = L;
for(int i = 0;i < num;i++){
ElementType a,b;
cin >> a >> b;
if(a != 0){
Attach(a,b,&Rear);
}
}
List t = L;
L = L->link;
delete(t);
return L;
}
void Attach(ElementType a,ElementType b,PtrToNode* Rear){
PtrToNode node = new Node;
node->coef = a;
node->expon = b;
node->link = NULL;
(*Rear)->link = node;
*Rear = node;
}
void Print( List L ){
bool flag = false;
if(L == NULL){
cout<<"0 0"<<endl;
return ;
}
PtrToNode cur = L;
while(cur){
if(flag){
printf(" ");
}else{
flag = true;
}
cout<< cur->coef <<" "<< cur->expon;
cur = cur->link;
}
cout <<endl;
return ;
}
List Add( List L1,List L2){
if (L1 == NULL){
return L2;
}
if(L2 == NULL){
return L1;
}
PtrToNode p1 = L1;
PtrToNode p2 = L2;
List L = new Node;
L->link = NULL;
PtrToNode cur = L;
while( p1 && p2){
PtrToNode node = new Node;
node->link = NULL;
ElementType temp;
if(p1->expon == p2->expon){
temp = p1->coef + p2->coef;
if(temp != 0){
Attach(temp,p1->expon,&cur);
}
p1 = p1->link;
p2 = p2->link;
}
else if(p1->expon > p2->expon){
Attach(p1->coef,p1->expon,&cur);
p1 = p1->link;
}
else{
Attach(p2->coef,p2->expon,&cur);
p2 = p2->link;
}
}
if(p1){
cur->link = p1;
}
if(p2){
cur->link = p2;
}
PtrToNode t = L;
L = L->link;
free(t);
return L;
}
List Mult(List L1, List L2 ){
if (L1 == NULL || L2 == NULL){
return NULL;
}
PtrToNode cur1 = L1;
PtrToNode cur2 = L2;
List L = new Node;
PtrToNode cur = L;
L->link = NULL;
while(cur2){
Attach(cur1->coef*cur2->coef,cur1->expon + cur2->expon,&cur);
cur2 = cur2->link;
}
cur1 = cur1->link;
PtrToNode t = L;
L = L->link;
free(t);
while(cur1){
cur2 = L2;
List pList = new Node;
PtrToNode tmp = pList;
pList->link = NULL;
while(cur2){
PtrToNode node = new Node;
node->coef = cur1->coef * cur2->coef;
node->expon = cur1->expon + cur2->expon;
tmp->link = node;
tmp = tmp->link;
cur2 = cur2->link;
tmp->link = NULL;
}
PtrToNode p = pList;
pList = pList->link;
free(p);
L = Add(L,pList);
cur1 = cur1->link;
}
return L;
}