Insertion Sort List
https://leetcode.com/problems/insertion-sort-list/
Insertion Sort List
Sort a linked list using insertion sort.
题目:插入排序
1 # Definition for singly-linked list.
2 # class ListNode:
3 # def __init__(self, x):
4 # self.val = x
5 # self.next = None
6
7 class Solution:
8 # @param {ListNode} head
9 # @return {ListNode}
10 def insertionSortList(self, head):
11 if head==None or head.next==None:return head
12 dummy=ListNode(0)
13 dummy.next=head
14 curr=head
15 while curr.next:
16 if curr.next.val<curr.val: #curr一直前进,直到找到非升序排列的项
17 pre=dummy
18 while pre.next.val<curr.next.val: #找到插入点
19 pre=pre.next
20 tmp=curr.next #将非升序项插入
21 curr.next=tmp.next
22 tmp.next=pre.next
23 pre.next=tmp
24 else:
25 curr=curr.next
26 return dummy.next