Skip to content

Commit 567106c

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
insettion-sort-list
1 parent 9b00e00 commit 567106c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

problems/insertion-sort-list.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Definition for singly-linked list.
2+
class ListNode(object):
3+
def __init__(self, x):
4+
self.val = x
5+
self.next = None
6+
7+
8+
class Solution(object):
9+
def insertionSortList(self, node):
10+
"""
11+
`pre_head` is a common technique that used in linked list problem.
12+
So we don't need to handle the edge case all the time.
13+
"""
14+
pre_head = ListNode(float('-inf'))
15+
pre_head.next = node
16+
pre = pre_head
17+
while node:
18+
if node.val>=pre.val: #see if node need to shift, if true, no need to shift this node
19+
pre = node
20+
node = node.next
21+
else:
22+
next_node = node.next
23+
self.remove(pre, node)
24+
self.insert(pre_head, node)
25+
node = next_node
26+
return pre_head.next
27+
28+
def remove(self, pre, node):
29+
pre.next = node.next
30+
31+
def insert(self, pre_head, node):
32+
curr = pre_head.next
33+
pre = pre_head
34+
while curr:
35+
if node.val<curr.val:
36+
pre.next = node
37+
node.next = curr
38+
break
39+
pre = curr
40+
curr = curr.next
41+

0 commit comments

Comments
 (0)