148. Sort List

148. Sort List
要求时间复杂度O(nlogn),归并排序,值得注意的是,找mid应该让fast = head.next,不然会出错。
# 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 == None or head.next == None:
return head
mid = self.findMid(head)
right = self.sortList(mid.next)
mid.next = None
left = self.sortList(head)
return self.merge(left, right)
def findMid(self, head):
if head == None:
return head
fast, slow = head.next, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
return slow
def merge(self, l1, l2):
if l1 == None:
return l2
if l2 == None:
return l1
dummy = p = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
if l1:
p.next = l1
if l2:
p.next = l2
return dummy.next