1,题目:
2.代码图:
3,代码文本;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* insertionSortList(struct ListNode* head){
if(head==NULL||head->next==NULL) //head->next==NULL这里是多余的。
return head;
//1.初始条件
struct ListNode* sortHead=head;
struct ListNode* cur=head->next;
sortHead->next=NULL; //****断开与后面链接。
while(cur) //终止条件,全部排完。
{
//3.迭代条件
struct ListNode* next=cur->next; //************第二步迭代
//将cur节点插入到前面有序链表中。
struct ListNode* p=NULL,*c=sortHead;
while(c) //找到在有序链表哪一个后面插入。
{
if(cur->val<c->val) //准备插才c的后面哦。
{
break;
}else
{
p=c;
c=c->next;
}
}
if(p==NULL) //比头小,相当于头插,
{
cur->next=c;
sortHead=cur; //新头
}else //相当与中间插入。
{
p->next =cur;
cur->next=c; //中间插入,头不用迭代。
}
cur=next;//第一步迭代
}
return sortHead;
}
4,思路,假设第一个有序,每次排一个,知道排完全部元素。