148. 排序链表
题目:
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
思路:
归并排序:分而治之
- 无限划分成小问题
- 再合并
# 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 and head.next == None:
return head
mid = self.findMid(head)
l1 = head
l2 = mid.next
mid.next = None
l1 = self.sortList(l1)
l2 = self.sortList(l2)
l3 = self.merge(l1,l2)
return l3
def merge(self,l1,l2):
"""
两个链表排序
"""
if l1 == None:
return l2
if l2 == None:
return l1
dummy = ListNode(-1)
cur = dummy
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
if l1 :
cur.next = l1
if l2:
cur.next = l2
return dummy.next
def findMid(self,head):
"""
快慢指针找到中间值
"""
if head == None and head.next == None:
return head
slow = head
fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow