帮忙看一下这个链表排序

来源:百度知道 编辑:UC知道 时间:2024/05/25 16:26:49
#include <stdio.h>
#include <malloc.h>

struct student
{
char name[20];
int score;
struct student *next;
};

struct student *p1,*p2,*head,*s,*tail,*small,*before,*k,*p;
int n=0,m=0;

struct student *creat()
{
p2=p1=(struct student *)malloc(sizeof(struct student));

while(scanf("%s%d",p1->name,&p1->score),p1->score!=0)
{ n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(sizeof(struct student));
}
p2->next=NULL;
return head;
}

struct student *paixu(struct student *head)
{
s=NULL; //新链表的头指针
while(head!=NULL) //当原链表的元素全部移到s中去,结束排列过程
{ k=NULL;
for(p1=head;p1->next!=NULL;p1=p1->next)
{
small=p1;

这个做得好麻烦哦,而且你的head 是全局变量,还搞返回值不是多此一举吗?
而且如果你要排序的数里面要求包含0的话你的就不能实现了。

while(scanf("%s%d",p1->name,&p1->score),p1->score!=0)
这里好像有点问题阿
不能终止输入阿

稍微修改了下,creat里面有内存释放...下面补上了...

#include <stdio.h>
#include <malloc.h>

struct student
{
char name[20];
int score;
struct student *next;
};

struct student *p1,*p2,*head,*s,*tail,*small,*before,*k,*p;
int n=0,m=0;

struct student *creat()
{
p2=p1=(struct student *)malloc(sizeof(struct student));

while(scanf("%s %d",p1->name,&p1->score),p1->score!=0)
{
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(sizeof(struct student));
}

p2->next=NULL;
free(p1); // 前面没把score值为0的p1释放,这里....
return head;
}

struct student *paixu(struct stud