多项式加法,有空的会的人帮忙看下,谢谢了。
#include<stdio.h>#include<malloc.h>
typedef int ElemType;
typedef struct node{
ElemType exp;
ElemType coef;
struct node *next;
}linklist;
struct node *creat( ) //创建链表。
{
struct node *p1,*head1,*p2;
head1=(struct node*)malloc(sizeof(struct node));
p1=(struct node*)malloc(sizeof(struct node));
scanf("%d %d",&p1->coef,&p1->exp);
head1->next=p1;
p1->next=NULL;
while(1)
{
p2=(struct node*)malloc(sizeof(struct node));
scanf("%d %d",&p2->coef,&p2->exp);
if(p2->exp<0) //当p2的指数小于0退出
break;
p1->next=p2;
p2->next=NULL;
p1=p2;
}
return(head1);
}
linklist *add(linklist *s1,linklist *s2)//加法函数
{
linklist *s=NULL;
linklist *p,*q;
linklist *p3;
linklist *rearc;
rearc=s;
p=s1->next;
q=s2->next;
while(q!=NULL&&p!=NULL)
{
if(p->exp==q->exp)
{
if(p->coef+q->coef!=0)
{
p3=(linklist *)malloc(sizeof(linklist));
p3->coef=p->coef+q->coef;
p3->exp=p->exp;
p3->next=NULL;
rearc->next=p3;
rearc=p3;
}
p=p->next;
q=q->next;
}
if(p->exp<q->exp)
{
p3=(linklist*)malloc(sizeof(linklist));
p3->coef=p->coef;
p3->exp=p->exp;
p3->next=NULL;
rearc->next=p3;
rearc=p3;
p=p->next;
}
if(p->exp>q->exp)
{
p3=(linklist*)malloc(sizeof(linklist));
p3->coef=q->coef;
p3->exp=q->exp;
p3->next=NULL;
rearc->next=p3;
rearc=p3;
q=q->next;
}
}
while(p!=NULL)
{
p3=(linklist*)malloc(sizeof(linklist));
p3->coef=p->coef;
p3->exp=p->exp;
p3->next=NULL;
rearc->next=p3;
rearc=p3;
p=p->next;
}
while(q!=NULL)
{
p3=(linklist*)malloc(sizeof(linklist));
p3->coef=q->coef;
p3->exp=q->exp;
p3->next=NULL;
rearc->next=p3;
rearc=p3;
q=q->next;
}
return s;
}
void BubbleSort(linklist *head) //冒泡排序链表
{
linklist *i=NULL,*j=NULL;
int temp_exp;
int temp_coef;
for(i = head->next; i!= NULL; i = i -> next)
for(j=i->next; j!=NULL; j=j->next)
if(i->exp>j->exp)
{
temp_exp=j->exp;
temp_coef=j->coef;
j->coef=i->coef;
j->exp=i->exp;
i->exp=temp_exp;
i->coef=temp_coef;
}
}
void print(linklist *head)//打印链表
{
linklist *current;
current = head->next;
while(current!=NULL)
{
if(current->coef!=0)
{
printf("%d %d ",current->coef,current->exp);
}
current=current->next;
}
printf("\n");
}
int main()//主函数
{
linklist *s1,*s2,*s3;
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
{
s1=creat();
BubbleSort(s1);
print(s1);
s2=creat();
BubbleSort(s2);
print(s2);
s3=add(s1,s2);
BubbleSort(s3);
print(s3);
}
return 0;
}