多项式相加

这是一份关于多项式相加的程序代码

#include<iostream.h>
#include<malloc.h>
#include <stdlib.h>
typedef struct LNode{
float coe; //系数
int exp; //指数
char sign; //运算符号
struct LNode *next;
}LNode,*LinkList;

void print(LinkList L)
{
LinkList q=L->next;
int flag=1;//项数计数器
while(q){
if(q->coe>0&&flag!=1) cout<<"+";
if(q->coe!=1&&q->coe!=-1){
cout<<q->coe;
if(q->exp==1) cout<<"X";
else if(q->exp) cout<<"X^"<<q->exp;
}
else{
if(q->coe==1){
if(!q->exp) cout<<"1";
else if(q->exp==1) cout<<"X";
else cout<<"X^"<<q->exp;
}
if(q->coe==-1){
if(!q->exp) cout<<"-1";
else if(q->exp==1) cout<<"-X";
else cout<<"-X^"<<q->exp;
}
}
q=q->next;
flag++;
}
cout<<endl;
}

void CreateList(LinkList L,int n)
{
LinkList p,q;
p=q=L;
L->next=NULL;
cout<<"请输入多项式的项数:";
cin>>n;
cout<<"请输入多项式的系数和指数:"<<endl;
for(int i=0;i<n;i++){
p=(LNode *)malloc(sizeof(LNode));
cout<<"请输入第"<<i+1<<"个系数和指数:";
cin>>p->coe;
if(p->coe>0)
p->sign='+';
if(p->coe< 0)
p->sign='-';
cin>>p->exp;
L->next=p;
L=p;
}
L->next=NULL;
L=q;
}


int compare(LinkList a, LinkList b)
{
if (a->exp < b->exp) return -1;
if (a->exp > b->exp) return 1;
return 0;
}




LinkList add(LinkList Pa,LinkList Pb)
{
LinkList head,p,temp,qa=Pa->next,qb=Pb->next;
float sum;
head=p=(LinkList)malloc(sizeof(LNode));//建立一个头结点
p->next=NULL;
if(Pa==NULL) return(Pb);
if(Pb==NULL) return(Pa);
while(qa&&qb) // Pa和Pb均非空
{
switch(compare(qa,qb))
{
case -1: // 多项式PA中当前结点的指数值小
p->next=qb;
p=qb;
qb=qb->next;
break;
case 0: // 两者的指数值相等
sum=qa->coe+qb->coe;
if(sum!=0)
{
qa->coe=sum;
p->next=qa;p=p->next;qa=qa->next;
temp=qb;qb=qb->next;free(temp);
}
else //如果系数和为零,则删除结点qa与qb
{
temp=qa->next;free(qa);qa=temp;
temp=qb->next;free(qb);qb=temp;
}
break;
case 1: // 多项式PB中当前结点的指数值小
p->next=qa;
p=qa;
qa=qa->next;
break;
}
}
if(qa!=NULL)

多项式相加相关文档

最新文档

返回顶部