-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSortList.py
More file actions
32 lines (28 loc) · 869 Bytes
/
InsertionSortList.py
File metadata and controls
32 lines (28 loc) · 869 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
27
28
29
30
31
32
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if not head or head.next is None:
return head
fd = ListNode(0)
fd.next = head
pre_ptr = fd.next
ptr = pre_ptr.next
while ptr is not None:
if ptr.val < pre_ptr.val:
q = fd
while q.next.val < ptr.val:
q = q.next
pre_ptr.next = ptr.next
ptr.next = q.next
q.next = ptr
ptr = pre_ptr.next
else:
pre_ptr = ptr
ptr = ptr.next
return fd.next