这不就是一个多项式求和吗?
#include
#include
#define LEN sizeof(struct entry)
struct entry{
int coef;
int expn;
struct entry *next;
};
void init(struct entry *strPer){
struct entry *p,*p1,*p2;
int m;
int n;
int k;
k=0;
p=strPer;
(*p).coef=0;
(*p).expn=-1;
p1=p2=(struct entry *) malloc (LEN);
printf("请输入多项式:\n");
scanf("%d%d",&p1->coef,&p1->expn);
p->next=NULL;
while (p1->coef!=0){
k=k+1;
if (k==1) p->next=p1;
else p2->next=p1;
p2=p1;
p1=(struct entry *) malloc (LEN);
scanf("%d%d",&p1->coef,&p1->expn);
}
p2->next=NULL;
printf("您输入的多项式是:\n");
p=strPer->next;
do {
if(p->coef==1){
printf("x^%d",p->expn);
}
else if (p->coef==-1){
printf("-x^%d",p->expn);
}
else{
if(p->coef>0) printf("+%dx^%d",p->coef,p->expn);
else printf("%dx^%d",p->coef,p->expn);
}
p=p->next;
}while(p!=NULL);
printf(" \n");
}
int cmp(int a,int b){
if (a if (a=b) return 0;
if (a>b) return 1;
}
struct entry * delFirst(struct entry *h,struct entry *q){
q=h->next;
h->next=(h->next)->next;
return (q);
}
void insFirst(struct entry *h,struct entry *q){
q->next=h->next;
h->next=q;
}
void append(struct entry *h,struct entry *q){
while (h->next!=NULL){
h=h->next;
}
h->next=q->next;
}
void iput(struct entry *strPer){
struct entry *p;
p=strPer->next;
printf("相加得到的多项式是:\n");
do{
if(p->coef==1){
printf("x^%d",p->expn);
}
else if (p->coef==-1){
printf("-x^%d",p->expn);
}
else{
if(p==strPer+1){
if(p->coef>0) printf("%dx^%d",p->coef,p->expn);
else printf("%dx^%d",p->coef,p->expn);
}
else{
if(p->coef>0) printf("+%dx^%d",p->coef,p->expn);
else printf("%dx^%d",p->coef,p->expn);
}
}
p=p->next;
}while(p!=NULL);
}
void main(){
struct entry *strPerA;
struct entry *strPerB;
struct entry *ha;
struct entry *hb;
struct entry *qa;
struct entry *qb;
int a;
int b;
int sum;
int k;
int h;
h=0;
strPerA=(struct entry *) malloc (LEN);
strPerB=(struct entry *) malloc (LEN);
if (strPerA!=NULL && strPerB!=NULL){
init(strPerA);
init(strPerB);
}
ha=strPerA;
hb=strPerB;
qa=ha->next;
qb=hb->next;
while(qa && qb){
a=qa->expn;
b=qb->expn;
k=cmp(a,b);
h=h+1;
switch (k){
case -1:
ha=qa;
qa=qa->next;
break;
case 0 :
sum=qa->coef+qb->coef;
if (sum!=0){
(*qa).coef=sum;
ha=qa;
}
else {
delFirst(ha,qa);
}
qb=delFirst(hb,qb);
//free(qb);
qb=qb->next;
qa=ha->next;
break;
case 1:
qb=delFirst(hb,qb);
insFirst(ha,qb);
qb=hb->next;
ha=ha->next;
break;
}
}
if (strPerB->next!=NULL) append(strPerA,strPerB);
iput(strPerA);
free(strPerB);
}