LeetCode 026. 重排链表

LCR 026. 重排链表

给定一个单链表 L的头节点 head ,单链表 L 表示为:

L0 → L1 → ... → Ln-1 → Ln

请将其重新排列后变为:

L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → ...

不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

复制代码
输入: head = [1,2,3,4]
输出: [1,4,2,3]

示例 2:

复制代码
输入: head = [1,2,3,4,5]
输出: [1,5,2,4,3]

提示:

  • 链表的长度范围为 [1, 5 * 104]

  • 1 <= node.val <= 1000

    Definition for singly-linked list.

    class ListNode:

    def init(self, val=0, next=None):

    self.val = val

    self.next = next

    class Solution:
    def reverse(self,head1):
    if head1 is None:
    return None
    pre=None
    cur=head1
    while cur is not None:
    cur_new=cur.next
    cur.next=pre
    pre=cur
    cur=cur_new
    return pre

    复制代码
      def reorderList(self, head: ListNode) -> None:
          """
          Do not return anything, modify head in-place instead.
          """
          if head is None:
              return
          
          slow=head
          fast=head
          while fast.next is not None and fast.next.next is not None:
              slow=slow.next
              fast=fast.next.next
          
          half_2=slow.next
          slow.next=None
          tail=self.reverse(half_2)
          
          cur_h=head
          while tail is not None:
              cur_h_new=cur_h.next
              cur_h.next=tail
              tail=tail.next
              cur_h.next.next=cur_h_new
              cur_h=cur_h_new
相关推荐
And_Ii3 小时前
leetCode 146. LRU 缓存
python·链表
心中有国也有家3 小时前
catlass 算子模板库中的 FlashAttention 高性能实现
笔记·算法
是娇娇公主~3 小时前
力扣——146.LRU缓存详解
算法·leetcode·缓存
我不是懒洋洋3 小时前
【C++】类和对象( 类的定义、实例化、 this指针、 C++和C语言实现Stack对比)
c语言·开发语言·数据结构·c++·经验分享·算法·visual studio
_深海凉_3 小时前
LeetCode热题100-路径总和 III
算法·leetcode·职场和发展
RTC老炮3 小时前
WebRTC AEC3 算法原理分析
算法·webrtc
炽烈小老头3 小时前
【每天学习一点算法 2026/05/20】省份数量
学习·算法
乐迪信息3 小时前
乐迪信息:港口夜间船舶巡查难,AI摄像机法全天候监测
人工智能·物联网·算法·计算机视觉·目标跟踪
sali-tec3 小时前
C# 基于OpenCv的视觉工作流-章74-线-线距离
图像处理·人工智能·opencv·算法·计算机视觉