链表相加函数出什么错了,代码一执行到那就结束了,不能输出最后相加的结果;
相加函数流程图:
正确的样例:
有问题的代码
#include<stdio.h>
#include<stdlib.h>
typedef struct PNODE
{
float coef;
int expn;
struct PNODE*next;
}PNODE;
PNODE *insert(PNODE *head,PNODE *s);
PNODE *creatPoly(PNODE *head);
void shuchu(PNODE *head);
PNODE *addPoly(PNODE *headA,PNODE *headB);
int main()
{
PNODE *headA,*headB;
headA=creatPoly(headA);
printf("\n输出多项式A:\n");
shuchu(headA);
headB=creatPoly(headB);
printf("\n输出多项式B:\n");
shuchu(headB);
headA=addPoly(headA,headB);
printf("\n输出两个多项式相加后的结果多项式:\n");
shuchu(headA);
return 0;
}
PNODE *creatPoly(PNODE *head)
{
int n,i;
head=NULL;
PNODE *s;
printf("输入该多项式的项数:");
scanf("%d",&n);
printf("\n输入多项式各项系数以及指数:");
for(i=1;i<=n;i++)
{
s=(PNODE*)malloc(sizeof(PNODE));
s->next = NULL;
scanf("%f %d",&s->coef,&s->expn);
if(i!=1)
{
head=insert(head,s);
}
else
{
head=s;
head->next=NULL;
}
}
printf("输入完成\n");
return head;
}
PNODE *insert(PNODE *head,PNODE *s)
{
PNODE *p,*pr;
p=pr=head;
while(p->next && p->next->expn < s->expn)
{
p=p->next;
}
if (p == head && p->expn > s->expn){
s->next = head;
head = s;
}
else{
s->next = p->next;
p->next = s;
}
return head;
}
void shuchu(PNODE *head)
{
PNODE *p;
p=head;
while(p!=NULL)
{
printf("\t%f %d,",p->coef,p->expn);
p=p->next;
}
printf("\n");
}
PNODE *addPoly(PNODE *headA,PNODE *headB)
{
PNODE *p1,*p2,*p3,*r; float sum=0;
p1=headA,p2=headB;
headA=NULL,p3=NULL;
if(p1&&p2)
{
if(p1->expn==p2->expn)
{
sum=p1->coef+p2->coef;
if(sum==0)
{
r=p1;
p1=p1->next;
free(r);
r=p2;
p2=p2->next;
free(r);
}
else{
p1->coef=sum;
p3->next=p1;
p3=p1;
p1=p1=p1->next;
r=p2;
p2=p2->next;
free(r);
}
}
else{
if(p1->expn<p2->expn){
if(p3!=NULL){
p3->next=p1;
p3=p1;
p1=p1->next;
}
else{
p3=p1;
p1=p1->next;
p3->next=NULL;
}
}
else{
if(p3!=NULL){
p3->next=p2;
p3=p2;
p2=p2->next;
}
else{
p3=p2;
p2=p2->next;
p3->next=NULL;
}
}
}
}
else{
if(p1!=NULL){
p3->next=p1;
}
else{
p3->next=p2;
}
}
return p3;
}