1009 Product of Polynomials (25 分)

多项式的乘法

#include<stdio.h>
#include<stdlib.h>
#define NULL 0
typedef struct PolyNode *Polynomial;
int length = 0;
struct PolyNode {
  double coef;
  int expon;
  Polynomial link;
};

void Attach(double c, int e, Polynomial* pRear){
  Polynomial P;
  P = (Polynomial)malloc(sizeof(struct PolyNode));
  P->coef = c;
  P->expon = e;
  P->link = NULL;
  (*pRear)->link = P;
  *pRear = P;
}

Polynomial ReadPoly (void){
  Polynomial P,Rear,t;
  int n;
  double c;
  int e;
  scanf("%d", &n);
  P=(Polynomial)malloc(sizeof(struct PolyNode));
  P->link=NULL;
  Rear=P;
  while(n--) {
    scanf("%d %lf", &e, &c);
    Attach(c, e, &Rear);
  }
  t=P;
  P=P->link;
  free(t);
  return P;
}


Polynomial Mult( Polynomial P1, Polynomial P2 ){
    Polynomial P, Rear, t1, t2, t;
    double c;
    int e;
    if (!P1 || !P2) return NULL;
    t1 = P1; t2 = P2;
    P = (Polynomial)malloc(sizeof(struct PolyNode)); P->link = NULL;
    Rear = P;
    while (t2) { /* 先用P1的第1项乘以P2,得到P */
        Attach(t1->coef*t2->coef, t1->expon+t2->expon, &Rear);
        t2 = t2->link;
    }
    t1 = t1->link;
    while (t1) {
        t2 = P2; Rear = P;
        while (t2) {
            e = t1->expon + t2->expon;
            c = t1->coef * t2->coef;
            while (Rear->link && Rear->link->expon > e)
            Rear = Rear->link;
            if (Rear->link && Rear->link->expon == e) {
                if (Rear->link->coef + c)
                Rear->link->coef += c;
                else {
                t = Rear->link;
                Rear->link = t->link;
                free(t);
                }
            }
            else {
            t = (Polynomial)malloc(sizeof(struct PolyNode));
            t->coef = c; t->expon = e;
            t->link = Rear->link;
            Rear->link = t; Rear = Rear->link;
            }
            t2 = t2->link;
        }
    t1 = t1->link;
    }
    t2 = P; P = P->link; free(t2);
    return P;
}

void Pint(Polynomial P){
  int flag = 0;
  if (!P) {	printf("0 0\n"); 	return;}
  while(P){
    if(!flag) flag = 1;
    else{
      printf(" ");
    }
    printf("%d %.1f", P->expon ,P->coef);
    P = P->link;
  }
  printf("\n");
}

int main(){
  Polynomial P1,P2,P;
  P1 = ReadPoly();
  P2 = ReadPoly();
  //Pint(P1);
  //Pint(P2);
  P = Mult(P1,P2);
  Pint(P);
  return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值