C语言 关于单链表的排序

来源:百度知道 编辑:UC知道 时间:2024/05/25 04:51:50
下列程序的功能为:建立一个由小到大的单链表,请纠正程序中存在的错误,使程序实现其功能
#include<stdio.h>
#include<malloc.h>
struct Link
{ int data;
struct Link *next;
} ;
void InsertList(struct Link *H,int n)
{
struct Link *p,*q,*s;
s=(struct Link *) malloc(sizeof(struct Link));
s->data=n;
q=H;p=H->next;
while(n>p->data && p)
{
q=p;p=p->next;
}
q->next=s;
s->next=q->next;
}
void main()
{
int a[]={12,3,45,67,7,65,10,20,35,55};
int i;
struct Link *H,*p;
H=(struct Link *) malloc(sizeof(struct Link));
H->next=NULL;
for(i=0;i<10;i++)
InsertList(H,a[i]);
p=H->next;
while(p)
{
printf("%4d",p->data);
p=p->next;
}
printf("\n");
}

q->next=s;
s->next=q->next;

这两句改为

s->next=p;
q->next=s;

其次
将InsertList函数里的
while(n>p->data && p)
改为
while(p && n>p->data)

需要首先判断p是否为空 为空则插入到链表最后
不然的话 直接先判断 n> p->data ,如果p为空,访问p->data会导致内存出错