【leetcode】92.反转链表II (Java)

题目描述

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表
在这里插入图片描述

输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]

提示:

  • 链表中节点数目为 n
  • 1 <= n <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= n

题解

1、新建头节点res,在left之前,所有节点依次添加res链表的最后。
2、到达left时,记录此时res的尾节点curRes。
3、从left到right之间的每个节点,利用头插法添加在curRes之后
4、添加之后,如果head还有剩余,curRes走到res链表结尾,curRes.next = head
5、最后返回res.next

class Solution {
   public ListNode reverseBetween(ListNode head, int left, int right) {
       ListNode res = new ListNode(), curHead = head, curRes = res;
       int count = 0;
       //left之前,按循序添加到res链表最后
       while (count < left - 1){
           curRes.next = head;
           head = head.next;
           curRes = curRes.next;
           count++;
       }
       //此时curRes为res链表尾,curHead为head剩下的头节点
       curRes.next = null;
       curHead = head;
       //开始反转,利用头插法把left到right之间的节点插入到curRes之后
       while (count < right){
           head = head.next;
           curHead.next = curRes.next;
           curRes.next = curHead;
           curHead = head;
           count++;
       }
       //如果head链表还有剩余,直接添加到res链表的最后
       if (curHead != null){
           while (curRes.next != null){
               curRes = curRes.next;
           }
           curRes.next = curHead;
       }
       return res.next;
   }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值