• 148排序链表


    class ListNode:
    def __init__(self, x):
    self.val = x
    self.next = None
    a = ListNode(1)
    b = ListNode(3)
    c = ListNode(2)
    d = ListNode(1)
    e = ListNode(5)
    a.next = b
    b.next = c
    c.next = d
    d.next = e
    # 这道题是用归并排序的方法
    class Solution:
    def sortList(self, head: ListNode) -> ListNode:
    # 首先判断链表是否只有一个节点,或者链表为空
    if not head or not head.next:return head
    # 定义两个快慢指针,用来找出链表的中间节点,用于等下递归的出口和入口
    slow,fast = head,head.next
    # 遍历链表,找出中间那个节点
    while fast and fast.next:
    slow,fast = slow.next,fast.next.next
    # 然后将链表分为两边,进行递归归并排序
    slow.next,mid = None,slow.next
    left = self.sortList(head)
    right = self.sortList(mid)
    # 定义一个节点,用来当做重新排序后链表的头结点
    node = ListNode(0)
    node1 = node
    # 遍历然后用于归并排序后的合成
    while left and right:
    if left.val > right.val:
    node.next,right = right,right.next
    else:
    node.next,left = left,left.next
    node = node.next
    node.next = left if left else right
    # 最后返回这个链表。
    return node1.next


    A = Solution()
    print(A.sortList(a))



  • 相关阅读:
    Nginx报400 Bad Request
    当前系统代理不是安全代理,是否信任
    nginx反向代理解决跨域问题
    SQL Prompt快捷键
    本地SQL Server怎么连接服务器上的数据库
    进制之间的转换
    计算机知识汇总
    C#语言学习记录
    excel常用技巧
    T-SQL学习记录
  • 原文地址:https://www.cnblogs.com/cong12586/p/13409059.html
Copyright © 2020-2023  润新知