148. Sort List
题目来源
https://leetcode.com/problems/sort-list/description/
题意分析
对链表进行排序,要求复杂度为 O(NlogN) O ( N l o g N )
题目思路
采用归并排序,与数组的归并排序在划分和合并时略有不同
代码
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None or head.next==None:
return head
mid = head
last = head
last = last.next
while last.next!=None and last.next.next!=None:
mid = mid.next
last = last.next.next
p = head
q = mid.next
mid.next = None
p = Solution().sortList(p)
q = Solution().sortList(q)
h = ListNode(0)
r = h
while p!=None or q!=None:
if q==None or (p!=None and p.val<=q.val):
r.next = p
p = p.next
else:
r.next = q
q = q.next
r = r.next
return h.next