# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类 the head node
# @return ListNode类
#
class Solution:
def sortInList(self , head: ListNode) -> ListNode:
# write code here
if not head or not head.next:
return head
def find_mid(head):
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def merge(l1:ListNode,l2:ListNode):
dummy = ListNode(0)
cur = dummy
while l1 and l2:
if l1.val<l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
if l1:
cur.next = l1
if l2:
cur.next = l2
return dummy.next
mid = find_mid(head)
right_head = mid.next
mid.next = None
left = self.sortInList(head)
right = self.sortInList(right_head)
return merge(left,right)
适合使用归并排序