148.Sort List === ###### tags: `Medium`,`Sorting`,`Two Pointers`,`Divide and Conquer` [148. Sort List](https://leetcode.com/problems/sort-list/) ### 題目描述 Given the `head` of a linked list, return the list after sorting it in **ascending order**. ### 範例 ##### Example 1: ![](https://i.imgur.com/Lq3dF76.png) ``` Input: head = [4,2,1,3] Output: [1,2,3,4] ``` ##### Example 2: ![](https://i.imgur.com/0wYAD6Q.png) ``` Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5] ``` ##### Example 3: ``` Input: head = [] Output: [] ``` ### 解答 #### Python Linked List 版 MergeSort ```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 not head or not head.next: return head prev, slow, fast = None, head, head # split while fast and fast.next: prev, slow, fast = slow, slow.next, fast.next.next prev.next = None left = self.sortList(head) right = self.sortList(slow) # merge def merge(left: Optional[ListNode], right: Optional[ListNode]) -> Optional[ListNode]: n = ListNode(0) ite = n while left and right: if left.val < right.val: ite.next = left left = left.next else: ite.next = right right = right.next ite = ite.next if left: ite.next = left if right: ite.next = right return n.next return merge(left, right) ``` > [name=Kobe Bryant] [time= Nov 23, 2022] ### Reference [回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)