/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;
struct ListNode* insertionSortList(struct ListNode* head){
//新建一个链表,最后返回插入完成
ListNode* newhead = NULL;
ListNode* cur = head;
//让cur遍历原链表
while(cur)
{
//让head往后走一下
head = cur->next;
ListNode* pos = newhead;
ListNode* prev = NULL;
//一,先找插入的位置
while(pos)
{
if(pos->val >cur->val)
break;
//利用prev标记pos的上一个位置,便于之后插入
prev = pos;
pos = pos->next;
}
//二,将cur插入到newhead中
if(pos == newhead)
{
//cur的值小于newhead的所有,选择头插
cur->next = newhead;
newhead = cur;
}
else{
//尾插和中间插入一样的,就合并在一起
cur->next = pos;
prev->next = cur;
}
//最后把head给cur
cur = head;
}
return newhead;
}

本文详细介绍了一种链表插入排序算法的实现过程,通过创建一个新的链表来逐步插入原链表中的节点,确保每次插入操作后新链表都是有序的。文章提供了完整的代码示例,展示了如何遍历原链表并找到每个节点在新链表中的正确位置。
302

被折叠的 条评论
为什么被折叠?



