需要四个指针
①last指针,初始指向head,指示排好序最后一个结点
②p工作指针
③new头指针之前的指针,固定不动,用于返回
④find指针,从头开始遍历已排好序的链表,指向插入位置的前驱
运行过程:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* insertionSortList(struct ListNode* head){
if(head==NULL || head->next==NULL)//如果为空链表或者只有一个结点
return head;
struct ListNode* new=(struct ListNode*)malloc(sizeof(struct ListNode));
//创建一个指向头结点的指针,固定不动
new->next=head;
struct ListNode* last=head;//已排好序的结点尾部,初始指向head
struct ListNode* p=head->next;//工作指针
while(p!=NULL)//当工作指针不空
{
if(p->val>=last->val)//若当前值>=已排好序的最后一个值
{
last=p;//把最后一个已经排好序的值变成p
p=last->next;//p指向下一个
}
else//当前值<last值
{
struct ListNode* find=new;//每次进入都创建一个指针指向头结点
while(find->next->val <= p->val)// <= ——稳定性
{
find=find->next;//若find值小于p值,则find移向下一个
}
//跳出以上循环的时候已经找到插入的前驱,注意插入的时候是要找前驱的!
last->next=p->next;
p->next=find->next;
find->next=p;
p=last->next;
}
}
return new->next;//返回最前面的指针即可
}