当前位置: 首页 > news >正文

力扣92.反转指定范围内的链表、25.k个一组反转链表

92.反转指定范围内的链表

/*** Definition for singly-linked list.* public class ListNode {*     int val;*     ListNode next;*     ListNode() {}*     ListNode(int val) { this.val = val; }*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode reverseBetween(ListNode head, int left, int right) {//left是第left个节点ListNode dummy=new ListNode(0,head);int count=0;ListNode pre=dummy,cur=dummy,tailAfter;while (right-->0){cur=cur.next;count++;if  (count==left-1){pre=cur;}}tailAfter=cur.next;cur.next=null;ListNode newHead=reverseList(pre.next);pre.next.next=tailAfter;pre.next=newHead;return dummy.next;}public ListNode reverseList(ListNode root){if (root==null || root.next==null) return root;ListNode newHead=reverseList(root.next);root.next.next=root;root.next=null;return newHead;}
}

25.k个一组反转链表

class Solution {public ListNode reverseKGroup(ListNode head, int k) {ListNode dummy=new ListNode(0,head);ListNode cur=dummy,pre=dummy,tail,tailAfter;int copyk;while (true){copyk=k;while (cur!=null && copyk-->0){cur=cur.next;}if (copyk>0 || cur==null) break;//为反转做准备tailAfter=cur.next;cur.next=null;ListNode newhead=reverseList(pre.next);pre.next.next=tailAfter;tail=pre.next;pre.next=newhead;//为下一次做准备pre=tail;cur=tail;}return dummy.next;}public ListNode reverseList(ListNode root){if (root==null || root.next==null) return root;ListNode newhead=reverseList(root.next);root.next.next=root;root.next=null;return newhead;}
}
http://www.dtcms.com/a/177137.html

相关文章:

  • 学习黑客Linux 系统状态管理
  • 不同OS版本中的同一yum源yum list差异排查思路
  • Android Studio根目录下创建多个可运行的模块
  • PDF文档压缩攻略
  • 【PhysUnits】2 Scalar<T> 标量元组结构体(scalar/mod.rs)
  • ABC 403
  • MySQL的基本操作
  • vue3+ts的watch全解!
  • 案例分享 | 攻克ADAS开发测试难题,实现单元动态测试新突破
  • 【Python】让Selenium 像Beautifulsoup一样,用解析HTML 结构的方式提取元素!
  • 分布式爬虫去重:Python + Redis实现高效URL去重
  • 【网络编程】二、UDP网络套接字编程详解
  • linux 怎么把trex-core-2.65用 crosstool-ng-1.27.0/编译
  • 96、数图求解(整数规划建模求解)
  • Python训练营打卡DAY18
  • 【anylogic_04】地铁站的人流仿真
  • Go 面向对象,封装、继承、多态
  • Win11 24H2首个热补丁下周推送!更新无需重启
  • 单地平面6层PCB设计实战:如何兼顾电源与信号完整性?
  • PyTorch常用命令(可快速上手PyTorch的核心功能,涵盖从数据预处理到模型训练的全流程)
  • Nacos源码—5.Nacos配置中心实现分析二
  • uniapp 搭配 uCharts
  • 回溯进阶(二):以解数独来深入了解映射
  • 【ARM AMBA AHB 入门 3.1 -- AHB控制信号】
  • 分区器(1)
  • ERP进销存系统源码,SaaS模式多租户ERP管理系统,SpringBoot、Vue、UniAPP技术框架
  • 易境通海外仓系统:如何高效管理尾程派送订单?
  • win安装anaconda 并切换软件源
  • VIVADO IP核整理(二)——FFT
  • win11下pip安装matplotlib超时的问题解决