zoukankan      html  css  js  c++  java
  • 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))



  • 相关阅读:
    python PIL生成图片
    ubuntu ftp安装配置
    PIL 字体居中显示
    python selenium cookie 转换成 request能用的cookie
    selenium给正在运行的火狐浏览器换代理ip
    python selenium 下载滑块验证码
    java 简单工厂 工厂模式
    java 装饰者模式
    java 观察者模式
    全排列
  • 原文地址:https://www.cnblogs.com/cong12586/p/13409059.html
Copyright © 2011-2022 走看看