跳到主要内容

Insertion Sort List

描述

Sort a linked list using insertion sort.

分析

代码

# Insertion Sort List
# Time complexity O(n^2), Space complexity O(1)
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
dummy = ListNode(float('-inf'))
#dummy.next = head

cur = head
while cur:
pos = self.findInsertPos(dummy, cur.val)
tmp = cur.next
cur.next = pos.next
pos.next = cur
cur = tmp
return dummy.next

def findInsertPos(self, head: ListNode, x: int) -> ListNode:
pre = None
cur = head
while cur and cur.val <= x:
pre = cur
cur = cur.next
return pre

相关题目