human
I am working on the file "01_Sort.ipynb".
The first task is:
Sort List

Sort a linked list in O(n log n) time using constant space complexity.
Can you write Python code for it?
assistant
#Here is the Python code you requested.

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        fast, slow = head.next, head
        while fast and fast.next:
            fast, slow = fast.next.next, slow.next
        second = slow.next
        slow.next = None
        l1 = self.sortList(head)
        l2 = self.sortList(second)
        return self.merge(l1, l2)
        

    def merge(self, l1, l2):
        dummy = node = ListNode(0)
        while l1 and l2:
            if l1.val <= l2.val:
                node.next = l1
                l1 = l1.next
            else:
                node.next = l2
                l2 = l2.next
            node = node.next
        node.next = l1 or l2
        
        return dummy.next