LeetCode #147 Insertion Sort List

Problem

Sort a linked list using insertion sort.

img
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
  3. It repeats until no input elements remain.

Examples

1
2
Input: 4->2->1->3
Output: 1->2->3->4
1
2
Input: -1->5->3->4->0
Output: -1->0->3->4->5

Method:

Time Complexity:

Space Complexity:

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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def print(self, head):
ptr = head
while ptr:
print(ptr.val, end=' ')
ptr = ptr.next

print('\n')
def helper()

def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head

dummy = ListNode(float('-inf'))
dummy.next = head
cur = head

while cur.next:
if cur.val <= cur.next.val:
cur = cur.next
else:
ptr = dummy
small = cur.next.val
while ptr.next != cur and ptr.next.val < small:
ptr = ptr.next

tmp = cur.next
cur.next = tmp.next
tmp.next = cur
ptr.next = tmp
self.print(dummy)
# cur = dummy.next


return dummy.next

Solution2

Method:

Time Complexity:

Space Complexity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def insertionSortList(self, head):
cur = dummy = ListNode(0)
while head:
if cur and cur.val > head.val:
cur = dummy
while cur.next and cur.next.val < head.val:
cur = cur.next
cur.next, cur.next.next, head = head, cur.next, head.next
return dummy.next