数据结构:一元稀疏多项式计算器(1)输入并建立多项式(2)输出多项式,输出形式为整数序列:项数,系数,指数,序列按指数降

1个回答

  • #include

    声明部分:源代码含有2个文件

    #include

    typedef struct pnode // 定义指针//

    {int coef; //定义系数//

    int exp; //定义指数//

    struct pnode *next;

    }pnode;

    pnode * creat() //creat函数用来存放多项式//

    {int m,n;

    pnode *head,*rear,*s;

    head=(pnode *)malloc(sizeof(pnode));

    rear=head;

    printf("n输入指数(按递增顺序输入):");

    scanf("%d",&m);

    printf("输入一元式系数(0为退出):");

    scanf("%d",&n);

    do

    {

    s=(pnode *)malloc(sizeof(pnode));

    s->coef=n; //n为系数//

    s->exp=m; //m为指数//

    rear->next=s;

    s->next=NULL;

    rear=s;

    printf("n输入指数(按递增顺序输入):");

    scanf("%d",&m);

    printf("输入一元式系数(0为退出):");

    scanf("%d",&n);

    }while(n);

    return head;

    }

    pnode * add(pnode *heada,pnode *headb)

    {pnode *headc,*a,*b,*s,*rearc;

    int sum;

    a=heada->next;b=headb->next;

    headc=(pnode *)malloc(sizeof(pnode));

    rearc=headc;

    //多项式的存放//都放到s中里//

    while(a!=NULL&&b!=NULL) //指数相等,则系数相加.//

    {

    if(a->exp==b->exp)

    { sum=a->coef+b->coef;

    if(sum)

    {s=(pnode *)malloc(sizeof(pnode));

    s->coef=sum;

    s->exp=a->exp;

    rearc->next=s;

    rearc=s;

    a=a->next;

    b=b->next;}

    else

    {a=a->next;

    b=b->next;

    }

    }

    else if(a->exp

    exp)

    //a指数如果小于b,则a放到s中//

    { s=(pnode *)malloc(sizeof(pnode));

    s->coef=a->coef;

    s->exp=a->exp;

    rearc->next=s;

    //用下一个结点s取代下一个c//

    rearc=s;

    a=a->next;

    }

    else //如果a的指数大,则b放到s中//

    { s=(pnode *)malloc(sizeof(pnode));

    s->coef=b->coef;

    s->exp=b->exp;

    rearc->next=s;

    rearc=s;

    b=b->next;

    }

    }

    if(a)

    {while(a!=NULL) //b空了放a中的项//

    {s=(pnode *)malloc(sizeof(pnode));

    s->coef=a->coef;

    s->exp=a->exp;

    rearc->next=s;

    s->next=NULL;

    rearc=s;

    a=a->next;

    }

    }

    else if(b)

    {while(b!=NULL) //a空了放b中的项//

    {s=(pnode *)malloc(sizeof(pnode));

    s->coef=b->coef;

    s->exp=b->exp;

    rearc->next=s;

    s->next=NULL;

    rearc=s;

    b=b->next;

    }}

    return headc;

    }

    void main()

    {pnode *a,*b,*c;

    printf("建立A:");

    a=creat();

    printf("n建立B:");

    b=creat();

    c=add(a,b);

    c=c->next;

    printf("%dx^%d",c->coef,c->exp);

    c=c->next;

    while(c!=NULL)

    {printf("+%dx^%d",c->coef,c->exp);

    c=c->next;

    }

    }

    参考资料: