Question
Given the head node of the linked list, please sort it in ascending order and return the sorted linked list.
# 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