148. Sort List

Given the head of a linked list, return the list after sorting it in ascending order.

Example 1:

Input: head = [4,2,1,3]
Output: [1,2,3,4]

Example 2:

Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]

Example 3:

Input: head = []
Output: []

Constraints:

Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?

Sort List - LeetCode

Top down approach:

class Solution:
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None or head.next is None:
            return head
        elif head.next.next is None:
            if head.val>head.next.val:
                tmp = head.val
                head.val = head.next.val
                head.next.val = tmp
            return head
        def findMid(head):
            fast = head
            slow = head
            while fast.next and fast.next.next:
                slow = slow.next
                fast = fast.next.next
            mid = slow.next
            slow.next = None
            return mid
        def merge(left, right):
            __head__ = ListNode()
            curr = __head__
            while left and right:
                if left.val>right.val:
                    curr.next = ListNode(right.val)
                    right = right.next
                else:
                    curr.next = ListNode(left.val)
                    left = left.next
                curr = curr.next
            if left:
                curr.next = left
            elif right:
                curr.next = right
            return __head__.next
        mid = findMid(head)
        left = self.sortList(head)
        right = self.sortList(mid)
        head = merge(left,right)
        return head

Bottom up approach:

Assume, n is the number of nodes in the linked list.