自己写的一个单链表直接插入排序算法 运行时总是出错 谢谢
#include <stdio.h>
#include <malloc.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student //定义节点
{
int num;
int score;
struct student *next;
};
struct student *creat(void)//建立链表
{
struct student *head,*p1,*p2;
n=0;
p1=p2=(struct student*)malloc(LEN);
scanf( "%d,%d ",&p1-> num,&p1-> score);
head=NULL;
while(p1-> num!=0)
{
n=n+1;
if(n==1)head=p1;
else p2-> next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
scanf( "%d,%d ",&p1-> num,&p1-> score);
}
p2-> next=NULL;
return head;
}
void print(struct student *head)//输出链表
{
struct student *p=head;
if(p!=NULL)
{
for(;p!=NULL;p=p-> next)
{
printf( "%d,%d\n ",p-> num,p-> score);
}
}
}
/*单链表直接插入排序*/
struct student * insert_sort(struct student *head)
{
struct student *h1,*p,*q,*t;
h1=head-> next;
head-> next=NULL;//此处将原链表一分为二,h1为等待插入的链表
while(h1!=NULL)//循环直至等待插入的链表为空!
{
printf( "#1\n ");
t=h1;//保存等待插入链表的头指针
h1=h1-> next;//h1后移
p=head;
q=head;
while(t-> num > p-> num && p!=NULL)/*进行节点大小比较*/
{
printf( "#2\n ");
q=p;
p=p-> next;
}
if(p==q) /*说明待排序点值最大,应排在首位*/
{
printf( "#3\n ");
head=t;
t-> next=p;
}
else /*待排序点应插入在中间某个位置q和P之间,
或者如果P为空则是尾部*/
{
printf( "#4\n ");
t-> next=p;
q-> next=t;
}
}
return head;
}
int main()
{
struct student *head;
printf( "input records:\n ");
head=creat();
head=insert_sort(head);
print(head);
return 0;
}
程序先先通过调用creat()来建立链表 然后调用head=insert_sort(head)排序 最后输出
编译能通过 单运行时候错误 printf( "#1\n ")等用来调试时用的
我输入3个数据分别是:
2,12
1,23
3,23
0,0(程序在输入0时候调用creat()结束)
输出:
#1
#3
#1
#2
#2
后程序中止运行
请大家帮我看看哪地方有错误?
[解决办法]
while(t-> num > p-> num && p!=NULL)/*进行节点大小比较*/
这一句可能会出现p== NULL的情况,改为:
while(p != NULL && t-> num > p-> num)/*进行节点大小比较*/
原因:&&的计算次序从左到右,所以调换一下次序,不然等p为NULL时,还没有判断p的值就去访问了。
------解决方案--------------------
这里错了:
------------------------------------------------
while(t-> num > p-> num && p!=NULL)/*进行节点大小比较*/
------------------------------------------------
应该是while(p!=NULL && t-> num > p-> num)
&&操作是如果左边的条件不满足就跳出,如果满足了才去判断右边的