struct student
{
int age;
char name[
15];
struct student
*next;
};
void main()
{
struct student
*head = NULL,
*p1,
*p2,
*p3,
*p4,
*p5,
*temp = NULL,
*start = NULL,
*temp1,
*temp2;
p1 = (struct student
*)malloc(sizeof(struct student));
p2 = (struct student
*)malloc(sizeof(struct student));
p3 = (struct student
*)malloc(sizeof(struct student));
p4 = (struct student
*)malloc(sizeof(struct student));
p5 = (struct student
*)malloc(sizeof(struct student));
temp = (struct student
*)malloc(sizeof(struct student));
gets(p1->name);
p1->age =
30;
gets(p2->name);
p2->age =
26;
gets(p3->name);
p3->age =
29;
gets(p4->name);
p4->age =
22;
gets(p5->name);
p5->age =
10;
head = p1;
p1->
next = p2;
p2->
next = p3;
p3->
next = p4;
p4->
next = p5;
p5->
next = NULL;
printf(
"\n排序前\n");
printf(
"head ");
while (head != NULL)
{
printf(
"-> %d ", head->age);
head = head->
next;
}
printf(
"-> NULL");
head = p1;
//头指针复位,为后续排序做准备
while (head != NULL)
{
start = head;
while (start->
next != NULL)
{
if (head->age > start->
next->age)
{
temp1 = head->
next;
//将将要进行比较的两个节点中的前者的地址备份
temp2 = start->
next->
next;
//将将要进行比较的两个节点中的后者的地址备份
*temp =
*(start->
next);
*(start->
next) =
*head;
*head =
*temp;
//此时交换了两个节点的所有元素,包括他们的指向,此时链表已断
head->
next = temp1;
//将交换过后的两个节点恢复为排序之前的指向,此时链表恢复
start->
next->
next = temp2;
}
start = start->
next;
}
head = head->
next;
}
head = p1;
//头指针复位,为后续打印做准备
printf(
"\n排序后\n");
printf(
"head ");
while (head != NULL)
{
printf(
"-> %d ", head->age);
head = head->
next;
}
printf(
"-> NULL");
getchar();
}