其他分享
首页 > 其他分享> > 反转n到m的链表节点

反转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;
        }
    }

 

标签:pre,head,ListNode,反转,next,链表,rightNode,null,节点
来源: https://blog.csdn.net/qq_57531795/article/details/120357131