c语言,两个一元多项式相加:

2024-11-08 18:44:38
推荐回答(2个)
回答1:

 #include 
#include 
#include 
#include 
#define Nc sizeof(Chain)
typedef struct chain
{
    int id,exp;
    struct chain*next;
}Chain;
Chain*creat(void)
{
    int a,b;
    Chain *h,*p,*r;
    h=(Chain*)malloc(Nc);
    p=h;
    while(1)
    {
        printf("输入系数:");//输入系数为0时表示输入结束。。。
        scanf("%d",&a);
        if(!a)break;
        printf("输入指数:");
        scanf("%d",&b);
        r=(Chain*)malloc(Nc);
        r->id=b;
        r->exp=a;
        p->next=r;
        p=r;
    }
    p->next=NULL;
    return h;
}
void print(Chain*h)
{
    Chain*p;
    p=h->next;
    while(p)
    {
        if(p->id==0)printf("%d",p->exp);
        else if(p->exp<0||p==h->next)
        printf("%dx^%d",p->exp,p->id);
        else printf("+%dx^%d",p->exp,p->id);
        p=p->next;
    }
    printf("\n");
}
Chain* multinomial(Chain *a,Chain *b)
{
    int x;
    Chain *h,*pa,*pb,*p,*q;
    Chain **o=NULL;
    h=(Chain*)malloc(Nc);
    p=(Chain*)malloc(Nc);
    pa=a->next;
    pb=b->next;
    p=h;
    while(pa&&pb)
    {
        if(pa->id==pb->id)
        {
            x=pa->exp+pb->exp;
            if(x)
            {
                q=(Chain*)malloc(Nc);
                q->id=pa->id;
                q->exp=x;
                p->next=q;
                p=q;
            }
                pa=pa->next;
                pb=pb->next;
        }
        else
        {
            o=(pa->idid)?&pa:&pb;
            q=(Chain*)malloc(Nc);
            q->id=(*o)->id;//->的结合度比*高
            q->exp=(*o)->exp;
            p->next=q;
            p=q;
            *o=(*o)->next;
        }
    }
    o=(NULL==pa)?&pb:&pa;
    while(*o)
    {
        q=(Chain*)malloc(Nc);
        q->id=(*o)->id;
        q->exp=(*o)->exp;
        p->next=q;
        p=q;
        *o=(*o)->next;
    }
    p->next=NULL;
    return h;
}
int main(void)
{
    Chain *p,*q;
    Chain *np;
    p=creat();
    q=creat();
    np=multinomial(p,q);
    print(np);
    return 0;
}

有问题欢迎指正

回答2:

通过单链表数据合并就可以解决这个问题