多项式(单链表)相等判断

题目:

 

结构体及链表创建:

typedef struct node{
    int coef;
    int exp;
    struct node* next;
}n,*pn;

pn create(int length){
    int *coef_array = new int[length] ;
    int *exp_array = new int[length] ;
    int coef,exp;
    for(int i=0;i<length;i++)
    {
        cout<<"input("<<i+1<<")coef:";
        cin>>coef;
        coef_array[i]=coef;
        cout<<"input("<<i+1<<")exp:";
        cin>>exp;
        exp_array[i]=exp;
    }
    for(int i=0;i<length;i++)
    {
        cout<<coef_array[i]<<"x^"<<exp_array[i]<<'+';
    }
    pn head,node,p;
    head=(pn)malloc(sizeof(n));  //分配空间
    p=(pn)malloc(sizeof(n));     //分配空间
    head->next=p;
    p->coef=coef_array[length-1];
    p->exp=exp_array[length-1];
    for(int i=length-2;i>=0;--i)
    {
        node=(pn)malloc(sizeof(n));  //分配空间
        node->coef=coef_array[i];
        node->exp=exp_array[i];
        node->next=NULL;
        p->next=node;
        p=p->next;
    }
    return head;
}

函数代码如下:

bool judge(pn heada,pn headb){
    pn pa=heada->next;
    pn pb=headb->next;
    int counta=0,countb=0;
    while(pa!=NULL){
        counta++;
        pa=pa->next;
    }
    while(pb!=NULL){
        countb++;
        pb=pb->next;
    }
    if(counta!=countb)
        return false;
    pa=heada->next;
    pb=headb->next;
    bool judge=false;
    while(pa!=NULL){
        cout<<pa->coef<<"x^"<<pa->exp<<":\n";
        while (pb!=NULL) {
            cout<<pb->coef<<"x^"<<pb->exp<<' ';
            if(pa->coef==pb->coef && pa->exp==pb->exp){
                judge=true;
                cout<<"matched!"<<endl;
                pb=headb->next;
                break;
            }
            pb=pb->next;
        }
        if(!judge)
            return false;
        judge=false;
        pa=pa->next;
    }
    return true;
}

 

点赞

发表评论