题解 | 单链表的排序 | 链表排序

单链表的排序

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

方法一: 将链表中的所有节点的值存储到列表,利用列表的排序方法重新排序,最后按顺序构建新的链表

方法二: 利用归并排序的思想,将1个链表划分为长度为链表长度一半的两个链表,层层递归,直到长度为1,然后按序合并

# 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 not head:
            return
        res=[]
        while head:
            res.append(head.val)
            head = head.next
        res.sort()
        a = ListNode(0)
        ans = a
        for r in res:
            a.next = ListNode(r)
            a = a.next
        return ans.next
class Solution:
    def sortInList(self , head ):
        if not head or  not head.next:
            return head
        
        cut = head
        
        slow = head
        fast = head
        # 查找中间节点
        while fast and fast.next:
            cut = slow
            slow = slow.next
            fast = fast.next.next
        left = head
        right = cut.next
        cut.next = None  # 断开左半个链表
        left = self.sortInList(left)
        right = self.sortInList(right)
        return self.merge(left, right)
        
    def merge(self, left, right):
        """合并两个已经排好序的链表"""
        guard = ListNode(0)
        p = guard
        while left and right:
            if left.val < right.val:
                guard.next = left
                left = left.next
            else:
                guard.next = right
                right = right.next
            guard = guard.next
        if left:
            guard.next = left
        if right:
            guard.next = right
        return p.next
全部评论

相关推荐

美团 后端开发 总包n(15%是股票)
点赞 评论 收藏
分享
一名愚蠢的人类:多少games小鬼留下了羡慕的泪水
投递荣耀等公司10个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务