📅  最后修改于: 2023-12-03 15:37:10.060000             🧑  作者: Mango
合并排序的链表是一种常用的排序算法,它将链表不断拆分,直到只剩一个节点,然后逐步合并,最终得到有序的链表。该算法时间复杂度为 O(nlogn)。
以下是合并排序的链表的示例代码实现,主要包括拆分和合并两个函数。
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
mid = self.getMid(head)
left = self.sortList(head)
right = self.sortList(mid)
return self.merge(left, right)
def getMid(self, head: ListNode) -> ListNode:
if not head:
return head
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
return mid
def merge(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
cur = dummy
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 if l1 else l2
return dummy.next
合并排序的链表是一种高效的排序算法,采用了分而治之的思想,大大提高了算法的时间效率。但是算法的实现并不简单,需要掌握链表的基本操作以及递归的思想。