对单链表进行插入排序,返回排序后头节点。插入排序:每步取一个待排节点,插入已排序部分的合适位置。
helper 作为已排序部分的虚拟头cur,在已排序链表中找到插入位置 precur 插入 pre 之后,继续处理下一节点class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (!head || !head->next) return head;
ListNode* helper = new ListNode(0); // 哨兵
ListNode* cur = head;
while (cur) {
ListNode* next = cur->next; // 保存下一节点
ListNode* pre = helper;
// 找到插入位置:pre->next 为首个大于 cur->val 的节点
while (pre->next && pre->next->val < cur->val)
pre = pre->next;
// 插入
cur->next = pre->next;
pre->next = cur;
cur = next;
}
ListNode* res = helper->next;
delete helper;
return res;
}
};
cur->next,必须先保存void insertionSort(vector& a) { for (int i = 1; i < a.size(); ++i) { int key = a[i], j = i - 1; while (j >= 0 && a[j] > key) a[j+1] = a[j--]; a[j+1] = key; } }
链表版无需移动元素,仅调整指针,但无法二分查找插入位置(无随机访问),故仍为 O(n²)。