Sort a linked list using insertion sort.
考察链表的插入排序
一开始在root.next=head;上卡了很久,后来想一想其实这是在一条新的list上进行的操作。
每次找一个节点,并将其插入的新的list上,是所谓插入排序
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode root(INT_MIN);
// root.next=head;
for(ListNode* cur=head;cur;){
//找到插入数据的点
ListNode* pos=&root;
while(pos->next && pos->next->val < cur->val) pos=pos->next;
//找到第一个pos->next值比cur->val大的元素
ListNode* next=cur->next;
cur->next=pos->next;
pos->next=cur;
cur=next;
}
return root.next;
}
};