#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
typedef struct list{
double coef;
int expn;
struct list *next;
}polyn;
polyn* creatpolyn(polyn*p,int m)
{
p=(polyn*)malloc(sizeof(polyn));
p->next=NULL;
while(m--){
polyn *temp=(polyn*)malloc(sizeof(polyn));
scanf("%lf %d",&temp->coef,&temp->expn);
temp->next=p->next;
p->next=temp;
}
return p;
}
int cmp(int a,int b){
if(a>b) return 1;
else if(a==b) return 0;
else return -1;
}
void delfirst(polyn*p,polyn*q)
{
p->next=q->next;
}
void insfirst(polyn*p,polyn*q)
{
q->next=p->next;
p->next=q;
}
void append(polyn*p,polyn*q)
{
polyn *temp=p;
while(1){
temp=temp->next;
if(!temp->next){
temp->next=q;
break;
}
}
}
void addpolyn(polyn*pa,polyn*pb)
{ int a,b;
double sum=0;
polyn *ha=pa;
polyn *hb=pb;
polyn *qa=ha->next;
polyn *qb=hb->next;
while(qa&&qb){
a=qa->expn;
b=qb->expn;
switch(cmp(a,b)){
case -1:ha=qa;
qa=qa->next;
break;
case 0:sum=qa->coef+qb->coef;
if(sum!=0.0){
qa->coef=sum;
ha=qa;
}
else{
delfirst(ha,qa);
free(qa);
}
delfirst(hb,qb);
free(qb);
qb=hb->next;
qa=ha->next;
break;
case 1:delfirst(hb,qb);
insfirst(ha,qb);
qb=hb->next;
ha=ha->next;
break;
}
}
if(!pb->next) append(pa,qb);
free(hb);
}
int main (void){
int numberofpa,numberofpb;
polyn *pa=NULL,*pb=NULL,*p=NULL;
scanf("%d %d",&numberofpa,&numberofpb);
pa=creatpolyn(pa,numberofpa);
printf("链表A设置完毕\n");
p=pa->next;
while(p!=NULL){
printf("%.2f %d\n",p->coef,p->expn);
p=p->next;
}
pb=creatpolyn(pb,numberofpb);
printf("链表B设置完毕\n");
addpolyn(pa,pb);
printf("加法完成\n");
while((pa->next)!=NULL){
pa=pa->next;
printf("%.2f %d\t",pa->coef,pa->expn);
}
return 0;
}
指针传递也是值传递,在里面对指针进行修改都要返回。