一元多项式相加

编写时出现的问题:
1.没有充分理解结构体的定义,无法正确使用
2.addlist() 函数中,未申请空间而直接使用导致无法访问
3.理解相加过程的思路
代码部分:

#include <stdio.h>
#include <malloc.h>
typedef struct polynode{
 int coef;//系数
 int exp;//指数
 struct polynode *next;
}polynode,*list;
list creatlist(int l);
void printlist(list poly);
list addlist(list polya,list polyb);

int main()
{
 list polya,polyb,polyc;//定义多项式,polyc为所求多项式和
 int la,lb;//定义多项式项数
 printf("The first polynode length : ");
 scanf("%d",&la);
 polya=creatlist(la);
 printf("The first polynode : P1(X) = ");
 printlist(polya);
 printf("\n");
 printf("The second polynode length : ");
 scanf("%d",&lb);
 polyb=creatlist(lb);
 printf("The second polynode : P2(X) = ");
 printlist(polyb);
 printf("\n");
 printf("ADD\n");
 printf("P1(X)+P2(X) = ");
 polyc=addlist(polya,polyb);
 printlist(polyc);
 return 0;
}

list creatlist(int l)
{
 list head,rear,s;//rear:用于尾插
 int i,c,e;
 head=(list )malloc(sizeof(struct polynode));
 rear=head;
 printf("Please enter the coef and exp : \n");
 for(i=0;i<l;i++)
 {
  s=(list )malloc(sizeof(struct polynode));
  scanf("%d %d",&c,&e);
  s->coef=c;
  s->exp=e;
  rear->next=s;
  rear=s;
 }
 rear->next=NULL;
 return head;
}
void printlist(list poly)
{
 list s;
 s=poly->next;
 while(s!=NULL)
 {
  printf("%dx^%d",s->coef,s->exp);
  s=s->next;
  if(s!=NULL)
   if(s->coef>0)
    printf("+");
  else
   printf("");
 }
 printf("\n");
}
list addlist(list polya,list polyb)
{
 list p,q,tail,temp,newpoly;
 int sum;
 p=polya->next;
 q=polyb->next;
 newpoly=(list )malloc(sizeof(struct polynode));//应分配空间进行存储
 tail=newpoly;
 while(p!=NULL&&q!=NULL)
 {
  if(p->exp < q->exp)
  {
   tail->next=p;
   tail=p;
   p=p->next;
  }
  else if(p->exp == q->exp)
  {
   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
  {
   tail->next=q;
   tail=q;
   q=q->next;
  }
 }
 if(p!=NULL)
 {
  tail->next=p;
  tail=p;
  p=p->next;
 }
 else
 {
  tail->next=q;
  tail=q;
  q=q->next;
 }
 return newpoly;
}

程序结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值