본문 바로가기

00/algorithm

Sort linked list (in Python)

반응형

Problem


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


Example 1:

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

Example 2:

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


Solution


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
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
 
class Solution(object):
    def merge(self, l1, l2) :
 
        fast = l1
        slow = l2
 
        dummy = ListNode(0)
        head = dummy
 
        while fast and slow :
            if fast.val < slow.val :
                dummy.next = fast
                dummy = dummy.next
                fast = fast.next
            else :
                dummy.next = slow
                slow = slow.next
                dummy = dummy.next
 
        dummy.next = fast or slow
        return head.next
 
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
 
        if head == None or head.next == None :
            return head
 
        slow = head
        fast = head.next
 
        if head.next != None: 
            
            while fast and fast.next :
                fast = fast.next.next
                slow = slow.next
 
            start = slow.next
            slow.next = None
 
            l1 = self.sortList(head)
            l2 = self.sortList(start)
 
            return self.merge(l1, l2)
cs




Source

https://leetcode.com/problems/sort-list/

반응형

'0 > algorithm' 카테고리의 다른 글

Linked List Cycle 2 (in Python)  (0) 2019.01.31
Minimum Depth of Binary Tree (in Python)  (0) 2019.01.29
Minimum Increment to Make Array Unique (in Python)  (0) 2019.01.25
Climbing Stairs (in Python)  (0) 2019.01.23
Add Binary (in Python)  (0) 2019.01.23