顺序存储结构的实现:例如,已知发f(x) = 8x^6 + 5x^5 - 10x^4 + 32x^2 - x + 10,

1个回答

  • #include

    #include

    #include

    #define N sizeof(struct duoxs)

    struct duoxs

    {

    int c;

    int e;

    struct duoxs *nest;

    }*head1,*head2;

    int main ( )

    {

    struct duoxs* get(int n);

    void print(struct duoxs *L);

    struct duoxs* jiangxu(struct duoxs *L);

    struct duoxs *add(struct duoxs *L1,struct duoxs *L2);

    struct duoxs *he;

    int n1,n2;

    printf("输入两个多项式的项数:n");

    scanf("%d%d",&n1,&n2);

    printf("输入第一个多项式的系数与指数:n");

    head1=get(n1);

    head1=jiangxu(head1);

    printf("输入第二个多项式的项数与指数:n");

    head2=get(n2);

    head2=jiangxu(head2);

    he=add(head1,head2);

    printf("两多项式之和为:n");

    print(he);

    system("pause");

    return 0;

    }

    struct duoxs *get(int n)//输入多项式

    { struct duoxs *p1,*p2,*L;

    int i;

    for(i=1;ic,&p1->e);

    p1->nest=NULL;

    }

    else

    {

    p2=(struct duoxs*)malloc(N);

    scanf("%d%d",&p2->c,&p2->e);

    p1->nest=p2;

    p1=p2;

    }

    }

    p1->nest=NULL;

    return (L);

    }

    void print(struct duoxs *L) //输出多项式

    {

    struct duoxs *p;

    int i=0;

    p=L;

    while(p!=NULL)

    {

    i++;

    if(i==1||p->cc,p->e);

    if(i!=1&&p->c>0)

    printf("+%dX^%d",p->c,p->e);

    p=p->nest;

    }

    printf("n");

    }

    struct duoxs* jiangxu(struct duoxs*L)//指数降序排列

    {

    int i;

    struct duoxs *p1,*p2;

    p1=L;

    while(p1->nest!=NULL)

    {

    p2=p1->nest;

    while(p2!=NULL)

    {

    if(p1->ee)

    {

    i=p1->e;

    p1->e=p2->e;

    p2->e=i;

    i=p1->c;

    p1->c=p2->c;

    p2->c=i;

    }

    p2=p2->nest;

    }

    p1=p1->nest;

    }

    return (L);

    }

    struct duoxs*add(struct duoxs*L1,struct duoxs*L2)

    //多项式相加

    {

    struct duoxs *L,*p,*p1,*p2,*q;

    p1=L1;

    p2=L2;

    int i=0;

    while(p1!=NULL&&p2!=NULL)

    {

    if(p1->e==p2->e)

    {

    i++;

    if(i==1)L=p=p1;

    else{p->nest=p1;p=p->nest;}

    p->c+=p2->c;

    p1=p1->nest;

    q=p2;

    p2=p2->nest;

    free(q);

    }

    else if((p1->e)>(p2->e))

    {

    i++;

    if(i==1)L=p=p1;

    else{p->nest=p1;p=p->nest;}

    p1=p1->nest;

    }

    else

    {

    i++;

    if(i==1)L=p=p2;

    else{p->nest=p2;p=p->nest;}

    p2=p2->nest;

    }

    }

    if(p1!=NULL)

    p->nest=p1;

    if(p2!=NULL)

    p->nest=p2;

    return (L);

    }