LeetCode #148 Sort List

Problem

Sort a linked list in O(n log n) time using constant space complexity.

Examples

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

Solution1

Method: Divide and Conquer

Time Complexity: O(n log n)

Space Complexity: O(1)

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

class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head

first = slow = head
fast = head

while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next

second = slow.next
slow.next = None
left = self.sortList(first)
right = self.sortList(second)

return self.merge(left, right)


def merge(self, left, right):
if not left or not right:
return left or right

if left.val > right.val:
left, right = right, left

head = prev = left
left = left.next

while left and right:
if left.val < right.val:
left = left.next
else:
new_left = prev.next
prev.next = right
next_right = right.next
right.next = new_left
right = next_right

prev = prev.next

prev.next = left or right

return head

Solution2

Method: Divide and Conquer without recursive

Time Complexity: O(n log n)

Space Complexity: O(1)

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
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None: return None

def getSize(head):
counter = 0
while(head is not None):
counter +=1
head = head.next
return counter

def split(head, step):
i = 1
while (i < step and head):
head = head.next
i += 1

if head is None: return None
#disconnect
temp, head.next = head.next, None
return temp

def merge(l, r, head):
cur = head
while(l and r):
if l.val < r.val:
cur.next, l = l, l.next
else:
cur.next, r = r, r.next
cur = cur.next

cur.next = l if l is not None else r
while cur.next is not None: cur = cur.next
return cur

size = getSize(head)
bs = 1
dummy = ListNode(0)
dummy.next = head
l, r, tail = None, None, None
while (bs < size):
cur = dummy.next
tail = dummy
while cur:
l = cur
r = split(l, bs)
cur = split(r, bs)
tail = merge(l, r, tail)
bs <<= 1
return dummy.next