class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
ans = ListNode(float("-inf"))
def helper(inserted):
cur = ans
while cur.next and cur.next.val < inserted.val:
cur = cur.next
inserted.next = cur.next
cur.next = inserted
while head:
helper(head)
head = head.next
return ans.next
到这里还没完,继续使用我的第二个技巧先穿再排后判空。由于这道题没有穿,我们直接排序和判空即可。
next 改变的代码一共两行,因此只需要关注这两行代码即可:
inserted.next = cur.next
cur.next = inserted
inserted 的 next 改变实际上会影响外层,解决方案很简单,留个联系方式就好。这我在上面的文章也反复提到过。
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
ans = ListNode(float("-inf"))
def insert(to_be_insert):
# 选择插入的位置,并插入
# 这里 to_to_insert 的 next 会被修改,进而影响外层的 head
while head:
# 留下联系方式
next = head.next
insert(head)
# 使用联系方式更新 head
head = next
return ans.next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
ans = ListNode(float("-inf"))
while head:
next = head.next
cur = ans
while cur.next and cur.next.val < head.val:
cur = cur.next
head.next = cur.next
cur.next = head
head = next
return ans.next
Java Code:
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode ans = new ListNode(-1);
while( head != null ){
ListNode next = head.next;
ListNode cur = ans;
while(cur.next != null && cur.next.val < head.val ){
cur = cur.next;
}
head.next = cur.next;
cur.next = head;
head = next;
}
return ans.next;
}
}
JS Code:
var insertionSortList = function (head) {
ans = new ListNode(-1);
while (head != null) {
next = head.next;
cur = ans;
while (cur.next != null && cur.next.val < head.val) {
cur = cur.next;
}
head.next = cur.next;
cur.next = head;
head = next;
}
return ans.next;
};
CPP Code:
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode dummy, *p;
while (head) {
auto *n = head;
head = head->next;
p = &dummy;
while (p->next && p->next->val < n->val) p = p->next;
n->next = p->next;
p->next = n;
}
return dummy.next;
}
};
复杂度分析
时间复杂度:$O(N^2)$,其中 N 为链表长度。
空间复杂度:$O(1)$。
大家对此有何看法,欢迎给我留言,我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 38K star 啦。大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。