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
相关推荐
Fuyo_11191 小时前
C++ AVL树保姆级详解:从平衡因子到四大旋转机制
java·c++·算法
jktantan1 小时前
每个节点 41 字节:把一棵百万节点树拆进 14 个 typed array
前端·javascript·vue.js·算法·typescript
揽星河..2 小时前
【C语言】猜数字游戏
c语言·算法·游戏
LabVIEW开发2 小时前
CTM-3 红外测温仪 + LabVIEW 温度怎么测?
算法·labview·测试·labview程序
纪念 2292 小时前
C++算法(六)
开发语言·c++·算法
Dumbness3 小时前
UIA 读微信群消息没有 id,怎么判断哪条是新的:后缀对齐在翻历史和撤回时整屏重报
python·算法
taka3 小时前
从 24x 到 141x:我用纯 Python 零依赖项目,扒开了 GPU 加速的性能黑洞
算法
UIU1144 小时前
P16237 [蓝桥杯 2026 省 B] 应急布线
数据结构·c++·算法·蓝桥杯
旖旎夜光4 小时前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
像风一样自由20204 小时前
2.如何用FastAPI把一个Python算法封装成HTTP服务
python·算法·fastapi