java 反转链表 II 反转从位置 left 到位置 right 的链表节点

1.题目

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
92. 反转链表 II

2.分析

  1. 主要是将left--right位置链表反转。
  2. 反转之前需要将left前面和right后面断开,以left位置为头结点进行反转
  3. 原来left前驱的next应该指向right位置的结点,left位置的结点的next应该是原来right位置结点的后继。
  4. 所以,反转之前要找到left的前驱,left位置结点right位置结点以及right位置的后继结点。

3.代码

public ListNode reverseBetween(int left, int right) {
        if (head == null || head.next == null) {
            return head;
        } else {
            ListNode newHead = new ListNode(-1);//创建傀儡结点
            newHead.next = head;

            //1.找到left的 前驱pre
            //从newHead 走 left-1 步
            ListNode pre = newHead;
            for (int i = 0; i < left - 1; i++) {
                pre = pre.next;
            }


            //2.找到 right 结点
            //再从pre 走 right-left+1 步
            ListNode rightNode = pre;
            for (int i = 0; i < (right - left + 1); i++) {
                rightNode = rightNode.next;
            }

            //3.截取left--right链表
            ListNode leftNode = pre.next;//left结点
            ListNode suc = rightNode.next;//right的后继

            //4.将 left之前 right之后 截断
            pre.next = null;
            rightNode.next = null;

            //5.反转left--right
            reverseLinkedList(leftNode);

            //6.将链表连接起来
            pre.next = rightNode;
            leftNode.next = suc;

            return newHead.next;
        }
    }

    public void reverseLinkedList(ListNode leftNode) {
        ListNode pre = null;
        ListNode cur = leftNode;
        while (cur != null) {
            ListNode curNext = cur.next;
            cur.next = pre;
            pre = cur;
            cur = curNext;
        }
    }

测试:

public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addlast(1);
        myLinkedList.addlast(2);
        myLinkedList.addlast(3);
        myLinkedList.addlast(4);
        myLinkedList.addlast(5);
        myLinkedList.display();
        System.out.println("===============");
        ListNode ret=myLinkedList.reverseBetween(2,4);
        myLinkedList.display(ret);
    }

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值