leetcode刷题_PYTHON(18):链表(18) 排序链表


class Solution: # 归并排序 def sortList(self, head: ListNode) -> ListNode: if not head or not head.next: return head left_end = self.find_mid(head) mid = left_end.next left_end.next = None left, right = self.sortList(head), self.sortList(mid) return self.merged(left, right) # 快慢指针查找链表中点 def find_mid(self, head): if head is None or head.next is None: return head slow,fast = head, head.next while fast is not None and fast.next is not None: slow=slow.next fast=fast.next.next return slow # 合并有序链表 def merged(self, left, right): res = ListNode() h = res while left and right: if left.val < right.val: h.next, left = left, left.next else: h.next, right = right, right.next h = h.next h.next = left if left else right return res.next 作者:yuer-flyfly 链接:https://leetcode-cn.com/problems/sort-list/solution/pai-xu-lian-biao-gui-bing-pai-xu-kuai-ma-2v1b/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
本文来自博客园,作者:秋华,转载请注明原文链接:https://www.cnblogs.com/qiu-hua/p/15259883.html

浙公网安备 33010602011771号