链表_leetcode148-链表归并排序

# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None


class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head

mid = self.getMid(head)

l = head
r = mid.next
mid.next =None
return self.merge(self.sortList(l),self.sortList(r))

def getMid(self,head):
if not head :
return head
fast = slow = head

while fast.next and fast.next.next:
slow = fast.next
fast = fast.next.next

return slow


def merge(self,p,q):
dummyHead = ListNode(0)
pre = dummyHead
while p and q:
if p.val < q.val:
pre.next = p
pre = pre.next
p = p .next
else:
pre.next = q
pre = pre.next
q = q.next

if p:
pre.next = p
else:
pre.next = q

return dummyHead.next
posted @ 2019-03-19 10:58  AceKo  阅读(161)  评论(0编辑  收藏  举报