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
相关推荐
啦啦啦啦啦zzzz24 分钟前
算法:回溯算法
c++·算法·leetcode
IT探索38 分钟前
Linux 查找文件指令总结
linux·算法
Lumos1861 小时前
51单片机从零到实战(完结)——后续学习路线建议
算法
稚南城才子,乌衣巷风流1 小时前
DFS序详解:原理、应用与实现
算法·深度优先·图论
稚南城才子,乌衣巷风流2 小时前
动态树(Dynamic Tree)数据结构详解
数据结构·算法
zander2582 小时前
114. 二叉树展开为链表
数据结构·链表·深度优先
变量未定义~2 小时前
最小生成树1(Prim模板)、最小生成树2(kruskal模板)、最近公共祖先(模板)
算法
这就是佬们吗3 小时前
Python入门⑤-异常处理、文件操作与实战项目
开发语言·数据库·python·算法·pycharm
LONGZETECH3 小时前
新能源汽车充电设备装配与调试仿真教学软件 技术架构与核心实现解析
大数据·算法·3d·unity·架构·汽车