-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinsertion_sort_list.py
59 lines (43 loc) · 1.52 KB
/
insertion_sort_list.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def insertionSortList(self, A):
dummy = ListNode(0)
dummy.next = A
prev = dummy
while prev.next:
tmp = prev
pmn = prev
while tmp.next:
if tmp.next.val < pmn.next.val:
pmn = tmp
tmp = tmp.next
# print(pmn.val, tmp.val)
# swap
it, nextIt = prev.next, prev.next.next
mn, nextMn = pmn.next, pmn.next.next
#self.printList(it)
#self.printList(mn)
if nextIt == mn:
prev.next = mn
mn.next = it
it.next = nextMn
else:
prev.next = mn
mn.next = nextIt
pmn.next = it
it.next = nextMn
#self.printList(prev)
prev = prev.next
return dummy.next
def printList(self, L):
Ls = []
while L:
Ls.append("{}".format(L.val))
L = L.next
print(" ->".join(Ls))