考点
题解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public: ListNode* insertionSortList(ListNode* head) { ListNode *dummyHead = new ListNode(-1, head); while (head->next != nullptr) { if (head->val > head->next->val) { ListNode *cur = dummyHead, *node = head->next; while (cur->next != nullptr && cur->next->val < node->val ) cur = cur->next; head->next = node->next; node->next = cur->next; cur->next = node; } else { head = head->next; } } return dummyHead->next; } };
|
思路
插入排序的精髓就在于,令当前元素之前的子数组为有序,然后判断当前元素应插入子数组的何种位置即可
令head
为有序子数组末尾,node
为head
的下一个元素
按照升序顺序,若node
大于等于head
,说明以node
结尾的子数组有序;那么head
应该向下移动
若node
大于head
,找到子数组中第一个大于node
节点的前一个节点,然后移动到它的后面完成插入操作
如此循环往复即可