-
Notifications
You must be signed in to change notification settings - Fork 0
/
147.py
48 lines (33 loc) · 953 Bytes
/
147.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = ['"wuyadong" <[email protected]>']
# 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
"""
root = ListNode(0)
root.next = head
p = root
while p.next:
# optimize
if p.val < p.next.val:
p = p.next
continue
pos = root
while pos.next != p.next and pos.next.val < p.next.val:
pos = pos.next
if pos.next == p.next:
p = p.next
else:
temp = p.next
p.next = temp.next
temp.next = pos.next
pos.next = temp
return root.next