Merge sort我研一上学期时候的笔记:
148. Sort List
简直就是我的笔记的代码版本。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
# step1 cut the list into two halves
prev, slow, fast = None, head, head
while fast is not None and fast.next is not None:
prev = slow
slow = slow.next
fast = fast.next.next
# break to two halves
prev.next = None
# step2 sort each half
left = self.sortList(head)
right = self.sortList(slow)
return self.merge(left, right)
def merge(self, left, right):
l = ListNode(0)
p = l
while left is not None and right is not None:
if left.val < right.val:
p.next = left
left = left.next
else:
p.next = right
right = right.next
p = p.next
if left is not None:
p.next = left
if right is not None:
p.next = right
return l.next