题目链接:https://leetcode.cn/problems/sort-list/
难度:中等
描述:
给你链表的头结点 head
,请将其按 升序 排列并返回 排序后的链表 。
提示:
节点数目:[0, 50000]
题解
# 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]:
def merge_tow_list(l1, l2):
dummy = ListNode()
cur = dummy
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
cur = cur.next
l1 = l1.next
else:
cur.next = l2
cur = cur.next
l2 = l2.next
cur.next = l1 if l1 else l2
return dummy.next
def merge_sort(head):
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
right_head = slow.next
slow.next = None
left = merge_sort(head)
right = merge_sort(right_head)
return merge_tow_list(left, right)
return merge_sort(head)