当前位置:   article > 正文

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

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;
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

测试:

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/209490
推荐阅读
相关标签
  

闽ICP备14008679号