02-线性结构2 一元多项式的乘法与加法运算

传送门

C++版本 

tip:注意最后一个测试点,需要打换行;

#include <stdio.h>
#include <stdlib.h>


//带头链表
typedef struct LNode* ptr;
typedef int Elem;
typedef struct LNode{
     Elem coe;
     Elem ex;
     ptr Next;
}LNode;
typedef ptr Link;

Link Add(Link a,Link b);
Link Mul(Link a,Link b);
Link Mul(Link a,LNode);
Link Init();
void output(Link a);
int main(){
    Link a,b;
    a = Init();
    b = Init();
    output(Mul(a,b));
    output(Add(a,b));
}

Link Init(){
    int n;
    scanf("%d",&n);
    Link h = (Link)malloc(sizeof(struct LNode));
    h->Next = NULL;
    Link r = h;
    while(n--){
        Elem coe,ex;
        scanf("%d%d",&coe,&ex);
        Link s = (Link)malloc(sizeof(struct LNode));
        s->coe = coe;
        s->ex = ex;
        r->Next = s;
        r = s;
    }
     r->Next = NULL;
     return h;
}

Link Mul(Link a,Link b){
     Link h = (Link)malloc(sizeof(struct LNode));
     h->Next = NULL;
     Link t2 = b->Next;
     while(t2){
        Link tp = Mul(a,*t2);
        h = Add(h,tp);
        t2 = t2->Next;
     }
   return h;
}


Link Mul(Link a,LNode b){   //传入两个指针,第一个为头指针,第二个为元素指针
    Link h =(Link)malloc(sizeof(struct LNode)),s;
    Link p = a->Next;
    Link r = h;
    h->Next = NULL;
    while(p){
        s =(Link)malloc(sizeof(struct LNode));
        s->coe = p->coe * b.coe;
        s->ex = p->ex + b.ex;
        r->Next = s;
        r = s;
        p = p->Next;
    }
    r->Next = NULL;
    return h;
}

Link Add(Link a,Link b){
     Link h,t1,t2,r,s;  //r尾指针,s为临时指针
     h = (Link)malloc(sizeof(struct LNode));
     h->Next = NULL;
     r = h;
     t1 = a->Next;
     t2 = b->Next;
     while(t1 && t2){
         s =(Link)malloc(sizeof(struct LNode));
          if(t1->ex > t2->ex){
              r->Next = t1;
              r = t1;
              t1 = t1->Next;
          }
          else if(t2->ex > t1->ex){
              r->Next = t2;
              r = t2;
              t2 = t2->Next;
          }
          else {
               if( t2->coe + t1->coe != 0){   s->coe=t2->coe + t1->coe ; s->ex = t1->ex ;r->Next = s ; r = s;}
               t1 = t1->Next;
               t2 = t2->Next;
          }
     }

     if(t1) r->Next = t1;
     else   r->Next = t2;
     return h;
}

void output(Link h){
    Link p = h->Next;
    if(!p)   printf("0 0\n");
    else{
      while(p){
        if(p->Next)printf("%d %d ",p->coe,p->ex);
        else printf("%d %d\n",p->coe,p->ex);
        p = p->Next;
        }
      }
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值