# Definition for singly-linked list. classListNode(object): def__init__(self, val=0, next=None): self.val = val self.next = next classSolution(object): # fixme: 归并排序(自底向上合并链表) defmerge(self, node1, node2): dummy = ListNode() pre = dummy while node1 is not None and node2 is notNone: if node1.val <= node2.val: pre.next = node1 pre = pre.next node1 = node1.next else: pre.next = node2 pre = pre.next node2 = node2.next if node1 is notNone: pre.next = node1 if node2 is notNone: pre.next = node2 return dummy.next
# fixme: 归并排序(自顶向下划分链表) defmerge_sort(self, head): if head is None or head.next is None: return head # 快慢指针寻找中间节点 slow = head fast = head while fast.next is not None and fast.next.next is notNone: slow = slow.next fast = fast.next.next # 找到中间节点之后断开链表 new_head = slow.next slow.next = None # 递归断开所有的节点 slow = self.merge_sort(head) fast =self.merge_sort(new_head)