反转n到m的链表节点

public ListNode reverseList2(ListNode head, int left, int right) {
        ListNode node = new ListNode(0);
        //为原链表定义一个头节点,方便操作
        node.next = head;

        //定位到left节点前一个位置
        ListNode pre = node;
        for (int i = 0; i < left - 1; i++) {
            pre = pre.next;
        }

        //定位到right的节点位置
        ListNode rightNode = pre;
        for (int i = 0; i < right; i++) {
            rightNode = rightNode.next;
        }

        //一个指针指向left节点,一个指针指向right的后一个节点位置,方便后续接上
        ListNode leftNode = pre.next;
        ListNode cur = rightNode.next;

        //切断连接
        pre.next = null;
        rightNode.next = null;

        //反转链表
        reverseListI(leftNode);

        //接上链表
        pre.next = rightNode;
        leftNode.next = cur;

        return node.next;
    }

    private void reverseListI(ListNode leftNode) {
        if (leftNode == null) {
            return;
        }
        ListNode pre = null;
        ListNode next = null;
        ListNode head = leftNode;

        while (head != null) {
            next = head.next;

            head.next = pre;

            pre = head;
            head = next;
        }
    }

 

上一篇:【LeetCode】101. 对称二叉树


下一篇:Java创建二叉树、二叉树的遍历