求大神看看这个程序错在哪里了(数据结构的链表问题)
题目要求给两个多项式,按指数降序输出它们相加的结果
可是我的输出结果是这样的
顺序出了问题。
小白刚学数据结构没多久找不到错误,还请大神们不吝赐教
程序代码:
#include<stdio.h> #include<stdlib.h> struct PloyNomial{ int coef; int expon; PloyNomial* next; }; void ReadPloy(PloyNomial* L,int i,int c,int e){ //写入多项式各项数据 PloyNomial*p = L; PloyNomial* q; int j; for(j=0; j<i-1; j++){ p = p->next; //找到插入的node 前一个位置 } q = (PloyNomial*)malloc(sizeof(PloyNomial)); q->coef = c; q->expon = e; //写入多项式数据 q->next = p->next; p->next = q; //调整指针 } PloyNomial *ADD(PloyNomial *headAH,PloyNomial *headBH)//实现多项式相加 { PloyNomial * Head_of_CH = (PloyNomial *)malloc(sizeof(PloyNomial));//创建CH的头结点 Head_of_CH->next = NULL; PloyNomial *p,*q; int sum,i; p=headAH->next;//分别使p和q指向第一个元素结点 q=headBH->next; for(i=1; p!=NULL||q!=NULL; i++) {if(p!=NULL&&q!=NULL){ if(p->expon < q->expon) { ReadPloy(Head_of_CH,i,p->coef,p->expon);//由于结果要求指数降序输出。所以此时应该输出p的数据 p = p->next; } else if(p->expon==q->expon) { sum = p->coef + q->coef; //系数相加 if(sum !=0) { p->coef=sum; ReadPloy(Head_of_CH,i,sum,p->expon); p=p->next; q=q->next; } else//如果和为零 { p=p->next; q=q->next; i--; } } else //若p->exp大于q->exp,由于结果要求指数降序输出。所以此时应该输出q的数据 { ReadPloy(Head_of_CH,i,q->coef,q->expon); q = q->next; } } if(p!=NULL&&q==NULL) //此时BH中的数据已经输出完毕,剩下的事情就是把AH中余下的所有项输出 { ReadPloy(Head_of_CH,i,p->coef,p->expon); p=p->next; } if(p==NULL&&q!=NULL) //此时AH中的数据已经输出完毕,剩下的事情就是把BH中余下的所有项输出 { ReadPloy(Head_of_CH,i,q->coef,q->expon); q=q->next; } } return Head_of_CH; } void print(PloyNomial *headCH){ //打印CH的元素 PloyNomial *p = headCH; p=p->next; while(p){ printf("%d %d, ",p->coef,p->expon); p=p->next; } } int main() { PloyNomial * Head_of_AH = (PloyNomial *)malloc(sizeof(PloyNomial));//创建AH的头结点 Head_of_AH->next = NULL; ReadPloy(Head_of_AH,1,1,0); ReadPloy(Head_of_AH,2,-3,6); ReadPloy(Head_of_AH,3,7,12); //写入AH各项的数据 PloyNomial * Head_of_BH = (PloyNomial *)malloc(sizeof(PloyNomial));//创建BH的头结点 Head_of_BH->next = NULL; ReadPloy(Head_of_BH,1,-1,4); ReadPloy(Head_of_BH,2,3,6); ReadPloy(Head_of_BH,3,-9,10); ReadPloy(Head_of_BH,4,8,14); //写入BH各项的数据 print(ADD(Head_of_AH ,Head_of_BH)); return 0; }