链表的排序和数组的排序思想是一样的。区别在于:数组时两个数之间的交换;而链表是每个节点之间的连接的变化。
不要试图用数组的交换思想来做链表排序,那样会很麻烦。只需要将需要的节点在原数组中删掉,形成一个新的链表。直至最后删掉原来数组中最后一个节点,加到排好序的新链表中就完成排序了。
思想:
遍历链表,找到最小数据的节点。将此节点在原链表中删掉,让这个节点成为新链表的头结点。然后,再在原链表中找最小数据的节点,将它从原链表中删掉,加到新节点的尾部。直至原链表指空,即原链表消失。
代码:
#include <stdio.h>
#include <stdlib.h>
//声明节点,重命名类型名
typedef struct person{
int age;
struct person* next;
}PER, *PPER;
//声明排序函数
struct person* sort(struct person* );
//封装所有函数到一个操作结构体中
struct operations {
struct person* (*p_create)(struct person*, int );
void (*p_show)(struct person* );
struct person* (*p_insert)(struct person* , int );
};
//依次显示链表中的数据
void show(struct person* phead)
{
while(phead){
printf("%d\t", phead->age);
phead = phead->next;
}
printf("\n");
}
//创建链表
struct person* insert(struct person* phead, int pa)
{
struct person* tmp = malloc(sizeof(struct person));
tmp->age = pa;
tmp->next = NULL;
if(phead == NULL)
return tmp;
else {
phead->next = tmp;
return tmp;
}
}
//定义操作结构体
struct operations ops = {
.p_show = show,
.p_insert = insert,
};
//链表排序
struct person* sort(struct person* phead)
{
struct person* pre_min = phead;
struct person* min = phead;
struct person* find = phead;
struct person* newhead , *neatail = NULL;
while(phead){
min = find = phead;
while(find->next != NULL){
if(min->age > find->next->age){
pre_min = find;
min = find->next;
}
find = find->next;
}
if(min == phead)
phead = phead->next;
else
pre_min->next = min->next;
min->next = NULL;
if(newhead == NULL)
newtail = newhead = min;
else
newtail = newtail->next = min;
}
return newhead;
}
int main()
{
struct person* head = NULL;
struct person* head2 = NULL;
head = ops.p_insert(head, -51);
head2 = head;
head2 = ops.p_insert(head2, 28);
head2 = ops.p_insert(head2, 11);
head2 = ops.p_insert(head2, 21);
head2 = ops.p_insert(head2, 23);
head2 = ops.p_insert(head2, -51);
ops.p_show(head);
struct person* newhead = sort(head);
ops.p_show(newhead);
return 0;
}
结果: