思想:和数组的插入排序的区别是链表节点是不连续的,借助一个数组来存放链表节点的指针,使他成为顺序的,就和数组的插入排序一样了,元素的移动不需要移动具体的节点(即不需要修改指针),只需要修改对应的值即可
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if (head == nullptr || head->next == nullptr)return head;
vector<ListNode*> s;
ListNode* cur = head;
s.push_back(cur);
cur = cur->next;
while (cur != nullptr){
s.push_back(cur);
int temp = cur->val;
int i= s.size()-2;//从当前节点的前一个节点开始比较
for (; i>=0; --i){
if (s[i]->val<temp){
break;//找到节点的插入位置,即第一个小于他的节点
}
else{
s[i+1]->val = s[i]->val;
}
}
s[i+1]->val = temp;//插入
cur = cur->next;//处理下一个节点
}
return head;
}
};