zoukankan      html  css  js  c++  java
  • 每日一题 LeetCode 143. 重排链表 【双指针】【链表逆转】【链表合并】

    题目链接

    https://leetcode-cn.com/problems/reorder-list/

    题目说明

    题解

    主要方法:链表找中位点;链表逆转;链表合并

    解释说明:

    1. 通过双指针找链表的中位点,将链表分成两部分

      • head: L(0) -> ... -> L((n+1)//2)
      • middle: L((n+1)//2+1) -> ... -> L(n)
    2. 将后部分链表逆转

      • middle: L(n) -> ... -> L((n+1)//2+1)
    3. 将 head 和 middle 合并

      • head: L(0) -> L(n) -> L(1) -> L(n-1) -> ... -> L((n+1)//2)

    代码示例:

    class Solution:
        def reorderList(self, head: ListNode) -> None:
            """
            Do not return anything, modify head in-place instead.
            """
            if not(head and head.next and head.next.next): return
            # 找中间位置
            fast, slow = head, head
            while fast.next and fast.next.next:
                fast, slow = fast.next.next, slow.next
            next_half = slow.next
            slow.next = None
            
            # 逆转
            middle = None
            while next_half:
                p, next_half = next_half, next_half.next
                p.next = middle
                middle = p
                
            # 合并
            res = head
            while middle:
                p = res.next
                res.next = middle
                middle = middle.next
                res.next.next = p
                res = p
    
  • 相关阅读:
    WebStorm2020.3.0及以下安装激活方法
    CSS随堂笔记【狂神说JAVA】
    HTML随堂笔记【狂神说JAVA】
    JAVA语言基础随堂笔记
    js 常用类和方法
    js 数组
    js 对象和函数
    js 基础语法
    JavaScript 简介
    PS基础
  • 原文地址:https://www.cnblogs.com/betternow/p/13849633.html
Copyright © 2011-2022 走看看