# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def merge(self, h1, h2):
dummy = tail = ListNode(None)
while h1 and h2:
if h1.val < h2.val:
tail.next, h1 = h1, h1.next
else:
tail.next, h2 = h2, h2.next
tail = tail.next
tail.next = h1 or h2
return dummy.next
def sortList(self, head):
if not head or not head.next:
return head
slow, fast = head, head
while fast.next and fast.next.next:
print(slow.val, fast.val)
slow, fast = slow.next, fast.next.next
mid = slow.next
slow.next = None
return self.merge(*map(self.sortList, (head, mid)))