【C和C++】多项式相乘

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

typedef struct polynomial
{
   int coef;
   int expn;
   struct polynomial *next;
}node;//单链表形式

node *creat()//用一个返回类型为结构体指针创建链表
{
    node *p,*q,*h;
    int expn,coef;
    h=(node*)malloc(sizeof(node));
    p=h;
    printf("enter your coef and expn\n");
    scanf("%d%d",&coef,&expn);
    while(coef!=0)//在项数为0的情况下退出输出
    {
        q=(node*)malloc(sizeof(node));
        q->coef=coef;q->expn=expn;
        p->next=q;
        p=q;
        scanf("%d%d",&coef,&expn);
    }
    p->next=NULL;
    return h;
}

void print(node *h)//显示链表内容
{
    node *p;
    p=h;
    while(p->next!=NULL)
    {
        p=p->next;
        if(p->next!=NULL)
        printf("%dX^%d+",p->coef,p->expn);
        else
        printf("%dX^%d\n",p->coef,p->expn);
    }

}

node *mul(node*ha,node*hb)//多项式相乘,此时的链表仅仅是经过了相乘,相同指数没有合并
{
    node*p1,*p2,*p,*h,*q;
    p1=ha;p2=hb;
    h=(node*)malloc(sizeof(node));
    p=h;
    while(p1->next!=NULL)
    {
        p1=p1->next;
        while(p2->next!=NULL)
        {
            p2=p2->next;
            q=(node*)malloc(sizeof(node));
            q->coef=p1->coef*p2->coef;
            q->expn=p1->expn+p2->expn;
            p->next=q;
            p=q;
        }
        p2=hb;
    }
        p->next=NULL;
        return h;
}

node *simp(node*hc)//将相同指数的项进行合并
{
    node *p,*q,*set;
    set=hc;
    p=hc->next;
    while(set->next!=NULL)
    {
        set=set->next;
        while(p->next!=NULL)
        {
            q=p;
            p=p->next;
            if(set->expn==p->expn)
            {
                set->coef+=p->coef;
                q->next=p->next;
                q=p;
                p=p->next;
                free(q);
            }
        }
        p=set->next;
    }
    return hc;
}


node *sort(node*h4)//将多项式按照降幂排列
{
    node *p,*q,*h;
    int temp1,temp2;
    q=h=h4;
    p=h4->next;
    while(h->next!=NULL)
    {
        while(q->next!=NULL)
        {
            if(p->expn>q->expn)
            {
                temp2=p->expn;
                p->expn=q->expn;
                q->expn=temp2;
                temp1=p->coef;
                p->coef=q->coef;
                q->coef=temp1;
            }
            p=p->next;
            q=q->next;
        }
        h=h->next;
        p=q=h;
        p=p->next;
    }
    return h4;
}

int main()
{
    printf("Hello world!\n");
    node *h1,*h2,*h3;
    printf("the first one is coef\n");
    h1=creat();
    h1=sort(h1);
    print(h1);
    printf("the second one is expen\n");
    h2=creat();
    h2=sort(h2);
    print(h2);
    printf("the third one is mul\n");
    h3=mul(h1,h2);
    h3=simp(h3);
    h3=sort(h3);
    print(h3);
    return 0;
}

 

posted on 2016-04-12 23:23  雪原那么远  阅读(445)  评论(0编辑  收藏  举报

导航