c语言链表排序问题

这段代码作用是构建链表然后按照成绩大小重新排列链表最后输出链表,构建链表我已经单独测试过没什么问题,可是加上重新排列链表后输出只能输出我最后输入的数据,其他的输出不出来,求大神解释下谢谢!

#include "stdio.h"
#include"malloc.h"

struct student
{
int num;
int score;
struct student * next;
};

struct student * sort()//这个是构建链表,经过测试没问题//
{
struct student * head;
struct student * p1;
struct student * p2;
head=NULL;
p1=(struct student * )malloc(sizeof(struct student));
if(p1==NULL)
{
printf("内存分配失败");
return 0;
}
printf("请输入学号和成绩用空格隔开\n");
scanf("%d %d",&p1->num,&p1->score);
while(p1->num!=0)
{
if(head==NULL)
{
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct student * )malloc(sizeof(struct student));
printf("请输入学号成绩用空格隔开\n");
scanf("%d %d",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}

struct student * newso(struct student * head2,struct student * newnod)//按成绩排列链表//
{
struct student * p1;
struct student * p2;

head2=newnod;
p1=head2;

if(p1==NULL||p1->num>newnod->num)
{
newnod->next=p1;
head2=newnod;
}
else
{
while(p1->next!=NULL&&p1->num<newnod->num)
{
p2=p1;
p1=p1->next;
}
if(p1->num>newnod->num)
{
p2->next=newnod;
newnod->next=p1;
}
else
{
p1->next=newnod;
newnod->next=NULL;
}
}
return head2;
}

void main()
{
struct student * head1;
struct student * head2;
struct student * k;
struct student * newnod;
int n=0;

printf("创建一个链表\n");
head1=sort();
head2=NULL;
k=head1;

while(k!=NULL)
{
newnod=(struct student *)malloc(sizeof(struct student));
newnod->num=k->num;
newnod->score=k->score;
head2=newso(head2,newnod);
k=k->next;
}
k=head2;
while(k!=NULL)
{
printf("%d\t%d",k->num,k->score);
k=k->next;
}
}

第1个回答  2016-03-18
相似回答
大家正在搜