题解 | #单链表的排序#

单链表的排序

http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

遍历链表的值用数组保存,然后修改链表的数值

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param head ListNode类 the head node
# @return ListNode类
#
class Solution:
    def sortInList(self , head ):
        # write code here
        if head is None or head.next is None:
            return head
        vals = []
        p = head
        while p:
            vals.append(p.val)
            p = p.next
        vals = sorted(vals)
        p = head
        for val in vals:
            p.val = val
            p = p.next
        return head

归并排序超时

class Solution:
    def sortInList(self , head ):
        # write code here
        if head is None or head.next is None:
            return head
        slow = head
        fast = head.next
        while fast and fast.next:
            slow = slow.next
            fast = fast.next
        new_list = slow.next
        slow.next = None
        left = self.sortInList(head)
        right = self.sortInList(new_list)
        dummy = ListNode(0)
        p = dummy
        while left and right:
            if left.val < right.val:
                p.next = left
                left = left.next
            else:
                p.next = right
                right = right.next
            p = p.next
        p.next = left if left is not None else right
        return dummy.next
全部评论

相关推荐

牛客771574427号:恭喜你,华杰
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务