mirror of https://github.com/doocs/leetcode.git
29 lines
883 B
Python
29 lines
883 B
Python
# Definition for singly-linked list.
|
|
# class ListNode:
|
|
# def __init__(self, val=0, next=None):
|
|
# self.val = val
|
|
# self.next = next
|
|
class Solution:
|
|
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
|
|
if head is None or head.next is None:
|
|
return head
|
|
slow, fast = head, head.next
|
|
while fast and fast.next:
|
|
slow = slow.next
|
|
fast = fast.next.next
|
|
l1, l2 = head, slow.next
|
|
slow.next = None
|
|
l1, l2 = self.sortList(l1), self.sortList(l2)
|
|
dummy = ListNode()
|
|
tail = dummy
|
|
while l1 and l2:
|
|
if l1.val <= l2.val:
|
|
tail.next = l1
|
|
l1 = l1.next
|
|
else:
|
|
tail.next = l2
|
|
l2 = l2.next
|
|
tail = tail.next
|
|
tail.next = l1 or l2
|
|
return dummy.next
|