-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion.py
More file actions
26 lines (24 loc) · 858 Bytes
/
Copy pathinsertion.py
File metadata and controls
26 lines (24 loc) · 858 Bytes
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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
sorted_head = ListNode(0)
sorted_head.next = head
sorted_tail = head
curr = head.next
while curr:
if curr.val >= sorted_tail.val:
sorted_tail = curr
curr = curr.next
else:
sorted_tail.next = curr.next
insert_pos = sorted_head
while insert_pos.next.val < curr.val:
insert_pos = insert_pos.next
curr.next = insert_pos.next
insert_pos.next = curr
curr = sorted_tail.next
return sorted_head.next