C链表问题
这是两个多项式相加的程序,l1和l2为两个链表的头结点,分别存储两个多项式的系数和指数,其中指数是按从大到小排列的,然后将其相加,再输出,请高手看看错在哪里了?小弟我很急啊。 #include "stdio.h"
#include "alloc.h"
typedef struct lianbiao{int c;int e;struct lianbiao *next;}link;
link *initlink(int n)
{int i;
link *head,*p,*s;
p=head=(link*)malloc(sizeof(link));
for(i=0;i<n;i++)
{s=(link*)malloc(sizeof(link));
scanf("%d%d",s->c,s->e);
p->next=s;
p=s;
}
p->next=NULL;
return head;
}
list(link *head)
{link *p;
p=head->next;
while(p!=NULL)
{printf("%d\t%d\n",p->c,p->e);p=p->next;}
printf("\n");
}
link *push(link *l1,link *l2)
{link *p,*s,*q,*head;
head=l1;
p=l1->next;s=l2->next;
l1->next=NULL;
while(p->next!=NULL&&s->next!=NULL)
{ if(p->e>s->e)
{l1->next=p;l1=p;p=p->next;}
else if(p->e<s->e)
{l1->next=s;l1=s;s=s->next;}
else if(p->c+p->c==0)
{q=p;p=p->next;free(q);
q=s;s=s->next;free(q);
}
else
{p->c=p->c+s->c;
l1->next=p;
l1=p;
q=s;
s=s->next;
p=p->next;
free(q);
}
}
if(p!=NULL)
l1->next=p;
else l1->next=s;
free(l2);
return head;
}
main()
{link *l1,*l2,*head;
l1=initlink(3);
l2=initlink(5);
list(l1);
list(l2);
head=push(l1,l2);
list(head);
}