1 """
2 链表插入排序
3 """
4 """
5 难点在于设计链表,插入排序时如何找到插入位置,并恢复好下一个遍历结点的位置
6 所以需要两个while循环,第一个是整体遍历,第二个是找插入位置
7 """
8 class ListNode:
9 def __init__(self, x):
10 self.val = x
11 self.next = None
12
13 class Solution:
14 def insertionSortList(self, head):
15 if not head or not head.next:
16 return head
17 first = ListNode(0)
18 first.next = head # 本题用三个指针来操作
19 pre = head
20 cur = head.next
21 while cur:
22 if pre.val < cur.val: # 如果有序,向后遍历
23 pre = cur
24 cur = cur.next
25 else:
26 pre.next = cur.next # 保存下一个要遍历的位置
27 insert = first # 用指针在前面找插入位置
28 while insert.next and insert.next.val < cur.val: # 找到插入位置
29 insert = insert.next
30 cur.next = insert.next # 插入结点
31 insert.next = cur
32 cur = pre.next # 指针归位
33 return first.next