跳至主要內容

BM2 链表内指定区间反转

微信公众号:储凡2023/4/6小于 1 分钟

BM2 链表内指定区间反转

题目链接

题目描述

区间反转.png

刷题思路

代码实现

export class ListNode {
  constructor(val, next) {
    this.val = (val == null ? 0 : val)
    this.next = (next == null ? null : next)
  }
}

export function reverseBetween(head, m, n) {
  let start = head
  let pre

  // 找到起点
  while (--m > 0) {
    pre = start
    start = start.next
  }

  // 找到终点
  let end = head
  while (--n > 0) {
    end = end.next
  }

  // 翻转中间部分
  let last = end.next
  end.next = null
  while (start != null) {
    const next = start.next
    start.next = last
    last = start
    start = next
  }
  // 将起点前的节点与终点相连
  if (pre == null)
    return end
  pre.next = end
  return head
}

一些建议

更新日志

2024/11/1 09:51
查看所有更新日志
  • ccf4c-style: 修复Eslint校验报错异常,修改部分代码和文档格式 (#184)
  • 5a2b2-feat: 移除markdown-cli模块,采用prettier校验文档格式
  • c0f2d-refactor: 升级vuepress相关版本,优化项目结构 (#137)
  • 06596-feat: 算法相关文档新增固定链接,优化导入代码配置
  • 9b9e4-feat: 算法相关文档更新,删除讨论链接 (#88)
  • c374b-feat: 更新一些文档的固定链接 (#87)
  • b0275-feat(markdownlint-cli): 添加markdown文档校验,支持lint脚本自动格式化文档
  • 5f1e1-feat: 导航栏、侧边栏内容修改,新增目录对应的文档
  • 2b8a3-docs: 新增一些文档,优化项目结构
  • 03b38-docs: 算法文档更新
  • 02ab1-style: 文档目录调整,修改mdEnhance配置
  • 871d0-feat: update
  • 2a2f2-feat(docs):update
贡献者: Chu Fan,chufan,142vip.cn,mmdapl,chufan443