博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【python/M/148】Sort List
阅读量:2171 次
发布时间:2019-05-01

本文共 1257 字,大约阅读时间需要 4 分钟。

题目

这里写图片描述

基本思路

归并排序(应用快慢指针将链表一分为二)

实现代码

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def sortList(self, head):        """        :type head: ListNode        :rtype: ListNode        """        # 归并排序        if head == None or head.next == None:            return head        fast = slow = head        while fast.next and fast.next.next:            slow = slow.next            fast = fast.next.next        head1,head2 = head,slow.next        slow.next = None        head1 = self.sortList(head1)        head2 = self.sortList(head2)        head = self.mergeList(head1,head2)        return head    def mergeList(self,head1,head2):        if head1 == None:            return head2        if head2 == None:            return head1        p = dummy = ListNode(0)        while head1 and head2:            if head1.val > head2.val:                p.next = head2                head2 = head2.next                p = p.next            else:                p.next = head1                head1 = head1.next                p = p.next        if head1 == None:            p.next = head2        if head2 == None:            p.next = head1        return dummy.next
你可能感兴趣的文章
Java并发编程:线程池的使用
查看>>
redis单机及其集群的搭建
查看>>
Java多线程学习
查看>>
检查Linux服务器性能
查看>>
Java 8新的时间日期库
查看>>
Chrome开发者工具
查看>>
【LEETCODE】102-Binary Tree Level Order Traversal
查看>>
【LEETCODE】106-Construct Binary Tree from Inorder and Postorder Traversal
查看>>
【LEETCODE】202-Happy Number
查看>>
和机器学习和计算机视觉相关的数学
查看>>
十个值得一试的开源深度学习框架
查看>>
【LEETCODE】240-Search a 2D Matrix II
查看>>
【LEETCODE】53-Maximum Subarray
查看>>
【LEETCODE】215-Kth Largest Element in an Array
查看>>
【LEETCODE】241-Different Ways to Add Parentheses
查看>>
【LEETCODE】312-Burst Balloons
查看>>
【LEETCODE】232-Implement Queue using Stacks
查看>>
【LEETCODE】225-Implement Stack using Queues
查看>>
【LEETCODE】155-Min Stack
查看>>
【LEETCODE】20-Valid Parentheses
查看>>