程序题 速求2 填空

来源:百度知道 编辑:UC知道 时间:2024/05/21 12:07:12
下面程序,先创建一个链表(链表中各结点未按学号由小到大排序),然后调用sort函数,将链表中各结点按学号由小到大排序。

#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(struct student)

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

struct student *creat(int n)
{
struct student *head=NULL,*p1=NULL,*p2=NULL;
int i;
for(i=1;i<=n;i++)
{ p1=(struct student *)malloc(LEN);
scanf("%ld",&p1->num);
scanf("%d",&p1->score);
p1->next=NULL;
if(i==1) head=p1;
else p2->next=p1;
p2=p1;
}
return(head);
}

void print(struct student *head)
{
struct student *p;
p=head;
while(p!=NULL)
{
printf("%8ld%8d",p->num,p->score);
p=p->next;
printf(&qu

链表的排序类似于数组的排序,思想一样
一般使用冒泡思想进行排序
你所需要做的就是编一个swap函数对链表相邻元素进行交换(相信学过链表这个不难,注意的是交换的时候不要忘记把这两个node的前驱节点指针指向他们,并让他们指向其后继node)
然后再sort函数做判断,调用swap函数完成冒泡
具体的代码相信只要你学过链表基础和冒泡一定能写出来!