求解:链表排序有问题 很诡异
自己写的一个链表排序程序,有奇怪问题,高手帮忙看下
程序代码:#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#define LEN sizeof(struct stu_info)
#define POSTU "\t\t%8s\t%8ld\t%3.1f\t%3.1f\t%3.1f\n"
#define POHEAD "\t\t 姓名 \t 学号 \t数学\tC语言\t英语\n"
#define PI "%s%ld%f%f%f"
typedef struct stu_info
{
char name[20];
long num;
float math_score;
float C_score;
float Eng_score;
struct stu_info *next;
}STU;
STU *Stu_list_Init(STU *L)//初始化
{
L=(STU *)malloc(LEN);
if(L==NULL)
{
exit(0);
}
L->next=NULL;
return L;
}
void Creat_list(STU *L)//创建 以end为结束创建标志
{
STU *tail,*p;
tail=L;
while(1)
{
p=(STU *)malloc(LEN);
if(p==NULL)
{
exit(0);
}
printf("\t\tname:");
scanf("%s",p->name);
if(strncmp(p->name,"end",3)==0)
{
free(p);
break;
}
printf("\t\tnumber:");
scanf("%ld",&p->num);
printf("\t\tmath:");
scanf("%f",&p->math_score);
printf("\t\tC:");
scanf("%f",&p->C_score);
printf("\t\tEng:");
scanf("%f",&p->Eng_score);
p->next=NULL;
tail->next=p;
tail=p;
}
tail->next=NULL;
}
void Print_list(STU *L)//打印链表
{
STU *p;
p=L->next;
if(p==NULL)
{
return;
}
printf(POHEAD);
while(p!=NULL)
{
printf(POSTU,p->name,p->num,p->math_score,p->C_score,p->Eng_score);
p=p->next;
}
}
void swap(STU *La,STU *Lb)
{
STU tmp,*t;
tmp=*La;
*La=*Lb;
*Lb=tmp;
t=(*La).next;// Do not lost it!Do not lost it! if lost this 3 sentences,that will lost some nodes!
(*La).next=(*Lb).next;
(*Lb).next=t;
}
void Sort_list(STU *L,int len)//冒泡排序
{
STU *pa;
int i,j;
// printf("\t\t%d\n",Getlen_list(L)); //这也有问题 在本函数调用求长度函数 会得到一个随机数 地址传递??
for(i=0;i<len-1;i++)
for(pa=L->next,j=0;j<len-1-i;j++,pa=pa->next)
if(pa->num>(pa->next->num))
swap(pa,pa->next);
}
int Getlen_list(STU *L)
{
STU *p;
int n;
p=L;
while(p->next!=NULL)
{
n++;
p=p->next;
p=p->next;
}
return n;
}
int main()
{
STU *stu;
stu=Stu_list_Init(stu);
// Creat_list(stu);
// -- 三个节点作测试--//
stu->next=&stu1;
strcpy(stu1.name,"xuhui");
stu1.num=2;
stu1.math_score=2;
stu1.Eng_score=2;
stu1.C_score=2;
stu1.next=&stu2;
strcpy(stu2.name,"joker");
stu2.num=1;
stu2.math_score=2;
stu2.Eng_score=2;
stu2.C_score=2;
stu2.next=&stu3;
strcpy(stu3.name,"jo");
stu3.num=3;
stu3.math_score=2;
stu3.Eng_score=2;
stu3.C_score=2;
stu3.next=NULL;
Print_list(stu);//问题出在这!!!!
Sort_list(stu,Getlen_list(stu));
Print_list(stu);
return 0;
}这么运行 程序是正常的 ,排序是正常的
但如果 把主函数以一个 Print_list(stu);注释掉之后 排序就出现段错误了···
想不通。 感觉 Print_list(stu);好想没有更改链表内容,为什么必须 Print_list(stu);之后排序才能正常?
排序函数有问题??









