题目描述:对链表进行插入排序。
本来这道题目是真的打算按一般的插入排序一样每次从后往前移动元素的,但是尝试之后发现并做不到,只好还是按照链表的顺序从前往后寻找插入点,然后一次性插入,也不知道这还叫不叫插入排序…… 这里有个感觉好用的技巧,一般链表操作我们总会给表头一个引用,比如 cur = head,然后对 cur 进行操作,以便最后找到表头。这道题这样是不行的,因为表头元素本身也在移动,所以给链表一个新表头,无论链表元素如何移动,新表头总是不动的,最后返回 new_head.next 就可以了。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
new_head = ListNode(0)
new_head.next = head
pre = head
cur = head.next
while cur:
next = cur.next
pre.next = next
p = new_head
while p.next and p.next.val < cur.val:
p = p.next
cur.next = p.next
p.next = cur
if p == pre:
pre = pre.next
cur = next
return new_head.next