题目链接: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 = nextclass Solution:def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:def merge_tow_list(l1, l2):dummy = ListNode()cur = dummywhile l1 and l2:if l1.val < l2.val:cur.next = l1cur = cur.nextl1 = l1.nextelse:cur.next = l2cur = cur.nextl2 = l2.nextcur.next = l1 if l1 else l2return dummy.nextdef merge_sort(head):if head is None or head.next is None:return headslow, fast = head, head.nextwhile fast and fast.next:slow = slow.nextfast = fast.next.nextright_head = slow.nextslow.next = Noneleft = merge_sort(head)right = merge_sort(right_head)return merge_tow_list(left, right)return merge_sort(head)
