Leetcode 147

Question

Solution

创建两个指针pre和cur,cur指向当前需要被排列的元素,pre指向需要放入的位置。找放入的位置的时候需要用比较pre.next.val和cur.next.val的大小关系。

每一次循环结束后都需要将pre重置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return
ans = pre = ListNode(0)
ans.next = head
cur = pre.next
while cur.next:
if cur.next.val < cur.val:
while pre.next.val < cur.next.val:
pre = pre.next
temp = pre.next
pre.next = cur.next
cur.next = cur.next.next
pre.next.next = temp
pre = ans
else:
cur = cur.next
return ans.next