编写一个算法,实现有序链表的归并排序。
有序链表的归并排序算法示例
对于有序链表的归并排序算法,可以采用递归的方式实现。下面是一个示例的实现代码:
# 定义链表节点
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 归并排序函数
def mergeSort(head):
if head is None or head.next is None:
return head
# 使用快慢指针找到链表中心
prev, slow, fast = None, head, head
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
prev.next = None
# 递归地对两个子链表进行排序
left = mergeSort(head)
right = mergeSort(slow)
return merge(left, right)
# 合并两个有序链表
def merge(l1, l2):
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