仅以此专栏,收藏一些见过的写过的特殊的代码
思路:新建一个空链表,将原无序链表的结点一个个拆下来,放入新链表中进行排序
题目:下面程序,先创建一个链表(链表中各结点未按学号由小到大排序),然后调用sort函数,将链表中各结点按学号由小到大排序
输入样例
3 (the 1st linked list, 2 students)
1 (code of no.1 student)
98 (score of no.1 student)
7 (code of no.2 student)
99 (score of no.2 student)
5 (code of no.3 student)
87 (score of no.3 student)
输出样例
1 98
7 99
5 87
1 98
5 87
7 99
代码:
#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(struct student)
struct student
{
long num;
int score;
struct student *next;
};
struct student *create(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("\n");
}
}
struct student *insert(struct student *head, struct student *stud)
{
struct student *p0,*p1,*p2;
p1=head;
p0=stud;
if(head==NULL)//空表
{
head=p0;
}
else
{
while( (p0->num > p1->num) && (p1->next!=NULL) )
/*遍历寻找目标结点,可能找到,此时p1指向目标结点;
也可能没找到,此时p1指向链表尾结点
*/
{
p2=p1;//备份目标结点的前驱结点的地址,方便以后处理前驱结点的指针域
p1=p1->next;
}
if( p0->num <=p1->num )//找到
{
if( head==p1 ) head=p0;//??
else p2->next=p0;
p0->next=p1;
}
else//没找到,在尾结点插入新结点
{
p1->next=p0;
}
}
return(head);
}
struct student *sort(struct student *head)//插入排序
{
struct student *h1=NULL,*h2=NULL,*p=NULL;
h1=head;
if(h1==NULL)
return head;
else
{
do
{
p=h1;
h1=h1->next;
p->next=NULL;
h2=insert(h2,p);
}
while(h1!=NULL);
}
return h2;
}
main()
{
struct student *head,*stu;
int n;
scanf("%d",&n);
head=create(n);//建表
print(head);
head=sort(head);//排序
print(head);
}
/*
测试数据
3
1
98
7
99
5
87
*/