LintCode Q173 Insertion Sort List in Python

  • Jinhai ZHOU
  • 5 Minutes
  • 2016年12月4日
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
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@return: The head of linked list.
"""
def insertionSortList(self, head):
# write your code here
# insertion sort
array = []
length = 0
current = head
while current is not None:
length += 1
array.append(current.val)
current = current.next
for i in xrange(1, length):
for j in xrange(i, 0, -1):
if array[j - 1] <= array[j]:
break
else:
array[j - 1], array[j] = array[j], array[j - 1]
if length == 0:
return None
head.val = array[0]
previous = head
for i in xrange(1, length):
node = ListNode(array[i])
previous.next = node
previous = node
return head
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。