为什么这个程序不能实现排序,急!!
这是一个实现多项式相加的程序。相加正确,但最后把多项式按指数从大到小排序不能成功,why?
# define len sizeof(struct dxs)
# define null 0
struct dxs
{
int xishu;
int zhishu;
struct dxs *next;
};
void print(struct dxs *head)
{
struct dxs *p;
p=head;
if(p!=null)
do
{
if(p-> xishu> 0)
printf( "+%dx^%d ",p-> xishu,p-> zhishu);
else if(p-> xishu <0)
{
printf( "%dx^%d ",p-> xishu,p-> zhishu);
}
p=p-> next;
}
while(p!=null);
printf( "\n ");
}
void sort(struct dxs *head)
{
struct dxs *p=head-> next,*q,*r;
if(p!=null)
{
r=p-> next;
p-> next=null;
p=r;
while(p!=null)
{
r=q-> next;
q=head;
while(q-> next!=null&&q-> next-> xishu> p-> xishu)
q=q-> next;
p-> next=q-> next;
q-> next=p;
p=r;
}
}
}
struct dxs *create()
{
int n=0;
int x;
int y;
struct dxs *head,*p1,*p2;
head=null;
p1=(struct dxs *)malloc(len);
scanf( "%d,%d ",&x,&y);
p1-> xishu=x;
p1-> zhishu=y;
p1-> next=null;
while(p1-> xishu!=0)
{
++n;
if(n==1)
head=p1;
else
p2-> next=p1;
p2=p1;
p1=(struct dxs *)malloc(len);
scanf( "%d,%d ",&x,&y);
p1-> xishu=x;
p1-> zhishu=y;
p1-> next=null;
}
free(p1);
return(head);
}
main()
{
struct dxs *pa,*pb,*pa1,*pb1,*pc,*head;
printf( "create pa now\n ");
pa=create();
printf( "%dx^%d ",pa-> xishu,pa-> zhishu);
print(pa-> next);
printf( "create pb now\n ");
pb=create();
printf( "%dx^%d ",pb-> xishu,pb-> zhishu);
print(pb-> next);
pa1=pa;
pb1=pb;
while(pb1!=null)
{ pc=pb1-> next;
while(pa1-> zhishu!=pb1-> zhishu&&pa1!=null)
{
pa1=pa1-> next;
}
if(pa1==null)
{
pa1=pa;
pb1-> next=pa-> next;
pa-> next=pb1;
pb1=pc;
}
else
{
pa1-> xishu+=pb1-> xishu;
pb1=pc;
pa1=pa;
}
}
printf( "%dx^%d ",pa-> xishu,pa-> zhishu);
print(pa-> next);
}
[解决办法]
sort函数中
r=q-> next;===> r=p-> next;
while(q-> next!=null&&q-> next-> xishu> p-> xishu)=====> while(q-> next!=null&&q-> next-> zhishu> p-> zhishu)
------解决方案--------------------
首先,你的指针变量q和p2没有初始化,仔细看看
struct dxs *head,*p1,*p2; /*明白没*/