社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

每日一道算法题--leetcode 148--链表排序(归并排序)--python

杉杉不要bug • 6 年前 • 759 次点击  
阅读 16

每日一道算法题--leetcode 148--链表排序(归并排序)--python

【题目描述】

【源代码】 归并排序

# 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 is None or head.next is None: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):#链表快慢指针找中点
        slow=fast=head
        if head is None :return slow
        while fast.next and fast.next.next:
            slow=slow.next
            fast=fast.next.next
        return slow
    def merge(self,l,r):
        a=ListNode(0)
        q=a
        while l and r:
            if l.val>r.val:
                q.next=r
                r=r.next
            else:
                q.next=l
                l=l.next
            q=q.next
        if l:
            q.next=l
        if r:
            q.next=r
        return a.next
复制代码
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/32094
 
759 次点击