数据结构之多项式add

测试数据不多,可能有bug,不过至少现在还能用~~

代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>

using namespace std;
int n,m;
typedef struct node
{
    int coef,exp;
    struct node *next;
}*Linklist,Lnode;

Linklist end_create(int num)
{
    Linklist temp,head=(Linklist)malloc(sizeof(Lnode));
    head->next=NULL,temp=head;
    int a,b,i;
    for(i=1;i<=num;i++)
    {
        scanf("%d%d",&a,&b);
        Linklist now=(Linklist)malloc(sizeof(Lnode));
        now->coef=a,now->exp=b;
        temp->next=now,temp=temp->next;
    }
    temp->next=NULL;
    return head;
}

void Destroy_list(Linklist head)
{
    Linklist node=head->next,temp=head;
    while(node&&temp)
    {
        temp=node,node=node->next;
        free(temp);
    }
    free(head);

}

void add(Linklist polya,Linklist polyb)
{
    Linklist p=polya->next,q=polyb->next,tail=polya;
    Linklist temp;
    ///利用了本来已有的链进行计算(以polya为头结点)
    while(p&&q)
    {
        if(p->exp<q->exp)
        {
            tail->next=p,tail=p,p=p->next;///tail为当前已经在最终表达式里面的最后一项
            ///同时也是p或者q的前驱
        }
        else if(p->exp>q->exp)
        {
            tail->next=q,tail=q,q=q->next;
        }
        else
        {
            if(p->coef+q->coef!=0)
            {
                p->coef=p->coef+q->coef;
                tail->next=p,tail=p,p=p->next;
                temp=q,q=q->next,free(temp);///注意free掉没用的q结点
            }
            else
            {
                temp=p,p=p->next,free(temp);
     ///什么?和tail没有关系?是的,因为tail本身的结点不会丢失,还是指向同一个结点
                temp=q,q=q->next,free(temp);
            }
        }
        if(p!=NULL)
        {
            tail->next=p;///直接连上p的剩余部分(也是完整的链)
        }
        else
        {
            tail->next=q;
        }
    }
}

void print(Linklist polya)
{
    Linklist temp=polya->next;
    while(temp)
    {
        printf("%d %d\n",temp->coef,temp->exp);
        temp=temp->next;
    }
}
int main()
{
    scanf("%d%d",&n,&m);///两个多项式分别有n项和m项
    Linklist polya=end_create(n);
    Linklist polyb=end_create(m);
    ///两个多项式的指数单增
    add(polya,polyb);
    //printf("%d %d\n",polya->next->coef,polya->next->exp);
    //printf("%d %d\n",polyb->next->coef,polyb->next->exp);
    print(polya);
    Destroy_list(polya),Destroy_list(polyb);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值