【数据结构】链表的应用-一元多项式的相加运算

例题2-11:请设计算法,实现一元多项式的相加运算。

#include<stdio.h>
#include<string.h>
using namespace std;
typedef struct PNode{
    int coef;
    int exp;
    struct PNode *next;
    PNode(int Coef=0,int Exp=-1,PNode *Next=NULL){
        coef=Coef;exp=Exp;next=Next;
    }
}PNode,*PolyList;
void OutputPolyList(PolyList &L){
    PolyList p=L->next;
    printf("f(x)=");
    if(p->coef==1){
        printf("x^(%d)%c",p->exp,p->next?' ':'\n');
    }else{
        printf("%dx^(%d)%c",p->coef,p->exp,p->next?' ':'\n');
    }
    p=p->next;
    while(p){
        if(p->coef==1){
            printf("x^(%d)%c",p->exp,p->next?' ':'\n');
        }else{
            printf("%+dx^(%d)%c",p->coef,p->exp,p->next?' ':'\n');
        }
        p=p->next;
    }
}
void InitPolyList(PolyList &L){

    PolyList p,Pre;
    L=new PNode(0,-1,NULL);
    Pre=L;
    int n,Exp;
    int Coef;
    printf("请输入n的值:\n");
    scanf("%d",&n);
    printf("依次输入n项:\n");
    for(int i=1;i<=n;i++){
        printf("第%d项:\n",i);
        printf("指数:");scanf("%d",&Exp);
        printf("系数:");scanf("%d",&Coef);
        printf("Exp : %d  Coef:%d\n",Exp,Coef);
        p=new PNode(Coef,Exp,NULL);
        Pre->next=p;
        Pre=p;
    }
}
void AddPolyList(PolyList &Pa,PolyList &Pb){
    PolyList Pre=Pa,pa=Pa->next,pb=Pb->next,s;
    while(pa&&pb){
        if( pa->exp < pb->exp ){
            Pre=pa; pa=pa->next;
        }else if( pa->exp > pb->exp ){
            Pre->next=pb;
            Pre=pb; pb=pb->next;
            Pre->next=pa;
        }else{
            int x=pa->coef + pb->coef;
            if(x){
                pa->coef=x; Pre=pa;
            }else{
                Pre->next=pa->next;
                delete pa;
            }
            s=pb; pb=pb->next; delete s;
            pa=Pre->next;
        }
    }
    if(pb) {
        Pre->next=pb;
    }
    delete(Pb);
}
int main(){
    PolyList Pa,Pb;
    InitPolyList(Pa);
    printf("Pa:\n");
    OutputPolyList(Pa);

    InitPolyList(Pb);
    printf("Pb:\n");
    OutputPolyList(Pb);

    printf("Pa+Pb:\n");
    AddPolyList(Pa,Pb);
    OutputPolyList(Pa);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值