Python solution

  • 0

    Basically the same thing as this one:

    I rewrote the merge part to make it easier to understand because I saw some questions around it.

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

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.