148. Sorted linked list

Question
Given the head node of the linked list, please sort it in ascending order and return the sorted linked list.
insert image description here

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None or head.next is None:
            return head
        mid = self.get_mid(head)
        l = head
        r = mid.next
        mid.next = None
        left = self.sortList(l)
        right = self.sortList(r)
        return self.merge(left, right)
        
    def get_mid(self,node):
        if node is None:
            return node
        fast = slow = node
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        return slow

    def merge(self, p, q):
        temp = ListNode(0)
        h = temp
        while p and q:
            if p.val < q.val:
                h.next = p
                p = p.next
            else:
                h.next = q
                q = q.next
            h = h.next
        if p:
            h.next = p
        if q:
            h.next = q
        return temp.next

Reference : https://blog.csdn.net/qq_34364995/article/details/80994110

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324339261&siteId=291194637