简繁EN

LeetCodeNo. 025

[LeetCode with Python] 147. Insertion Sort List

Contents

Problem

Problem page: https://leetcode.com/problems/insertion-sort-list/
Topics: Linked List, Sort
Difficulty: Medium
Similar problems: (M) Sort List

Sort a linked list using insertion sort.


Analysis

Insertion sort on a linked list. I first saw someone's C++ solution online. It creates a new linked list and inserts the next node into it each time. I tried the same thing in Python, but it timed out. Later I changed it to sort the original linked list in place without creating a new one. I also added a check to avoid doing a lot of unnecessary work when the list is already sorted (because the first version timed out when the judge gave it a really long linked list that was already sorted -_-).


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:

# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if None == head or None == head.next:
return head

new_head = ListNode(0)
new_head.next = head

last = new_head.next
cur = new_head.next.next
while None != cur:
if cur.val >= last.val:
last = cur
cur = cur.next
continue
ins = new_head
while None != ins.next and ins.next.val <= cur.val: # stable sort
ins = ins.next
last.next, cur.next, ins.next, cur = cur.next, ins.next, cur, cur.next

return new_head.next

Article link: https://xnerv.wang/en/leetcode-insertion-sort-list/