Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
O(n2)的方法并不能通过
归并排序
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
#找到中间节点
fast,slow = head,head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
#断开
fast = slow
slow = slow.next
fast.next = None
l1 = self.sortList(head)
l2 = self.sortList(slow)
return self.merge(l1,l2)
def merge(self,l1,l2):
pre = tail = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
tail.next = l1
tail = l1
l1 = l1.next
else:
tail.next = l2
tail = l2
l2 = l2.next
tail.next = l1 or l2
return pre.next