原题地址
题解:
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution:def insertionSortList(self, head: ListNode) -> ListNode:if head is None:return headhead_node = ListNode(0) # 创建一个临时节点(空列表)head_node.next = head # 将原来列表的头节点挂到新的链表上cur_node = head.next # cur_node代表当前需要进行排序的节点last_sorted_node = head # last_sorted_node代表已经经过了排序的所有结点的尾部节点# 使用第二个节点开始排序,第一个节点作为基点while cur_node: # 一直循环到链表尾部if last_sorted_node.val <= cur_node.val: # 判断当前排序节点值和已排序部分尾部节点值的关系last_sorted_node = cur_node # 如果cur >= last_sorted_node, 不需要插入else: # 如果cur < last_sorted_node, 需要将cur_node插入到已排序部分中prev_node = head_node # 针对已排序部分,从头部开始遍历,寻找合适的位置while prev_node.next.val <= cur_node.val:prev_node = prev_node.nextlast_sorted_node.next = cur_node.next # 将cur_node插入到指定位置上cur_node.next = prev_node.nextprev_node.next = cur_nodecur_node = last_sorted_node.nextreturn head_node.next
