148.Sort List

tags: Medium,Sorting,Two Pointers,Divide and Conquer

148. Sort List

題目描述

Given the head of a linked list, return the list after sorting it in ascending order.

範例

Example 1:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Example 3:
Input: head = []
Output: []

解答

Python

Linked List 版 MergeSort

# 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)

Kobe Bryant Nov 23, 2022

Reference

回到題目列表