测试数据不多,可能有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;
}