第1个回答 2014-04-04
#include<stdlib.h>
#include<stdio.h>
typedef struct Polynode
{
int coef;
int exp;
Polynode *next;
}Polynode,*Polylist;
Polylist polycreate()
{
Polynode *head,*rear,*s;
int c,e;
head=new Polynode;/*建立多项式的头结点, rear 始终指向单链表的尾*/
rear=head;
printf("请输入系数coef与指数exp:");
scanf("%d%d",&c,&e);/*键入多项式的系数和指数项*/
while(c!=0)/*若c=0,则代表多项式的输入结束*/
{
s=new Polynode;/*申请新的结点*/
s->coef=c;
s->exp=e;
rear->next=s ;/*在当前表尾做插入*/
rear=s;
scanf("%d%d",&c,&e);
}
rear->next=NULL;/*将表的最后一个结点的next置NULL,以示表结束*/
return head;
}
Polylist add(Polylist polya,Polylist polyb)
{
Polynode *p,*q,*tail,*temp;/*p和q分别指向polya和polyb链表中的当前计算结点*/
int sum;
p=polya->next;
q=polyb->next;
tail=polya;/*tail指向和多项式链表中的尾结点*/
while(p&&q)
{
if(p->exp<q->exp)
{
/*将p结点加入到和多项式中*/
tail->next=p;
tail=p;
p=p->next;
}
else if(p->exp==q->exp)
{/*若指数相等,则相应的系数相加,若系数为0则删除p,q节点*/
sum=p->coef+q->coef;
if(sum!=0)
{
p->coef=sum;
tail->next=p;
tail=p;
p=p->next;
temp=q;
q=q->next;
free(temp);
}
else
{
temp=p;
p=p->next;
free(temp);
temp=q;
q=q->next;
free(temp);
}
}
else
{
/*将q结点加入到和多项式中*/
tail->next=q;
tail=q;
q=q->next;
}
}
/*将多项式polya或polyb中剩余的结点加入到和多项式中*/
if(p!=NULL)
tail->next=p;
else
tail->next=q;
return polya;
}
void output(Polylist L)
{
Polynode *p;p=L->next;
printf("该多项式为:");
while(p)
{
printf("%d",p->coef);printf("x^");printf("%d",p->exp);
if(p->next)printf("+");
p=p->next;
}
printf("\n");
}
int main()
{
Polylist pa,pb,psum;
pa=polycreate();output(pa);
pb=polycreate();output(pb);
output(add(pa,pb));
system("pause");
}
你看下吧本回答被提问者采纳