LeetCode92. 反转链表 II

☆☆☆思路:虚拟头节点 + 反转链表

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || head.next == null || m == n) return head;
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode start = dummyHead;
        // Setp1:找到第 m-1 个节点,即待反转节点的前一个节点
        for (int i = 1; i < m; i++) {
            start = start.next;
        }
        // cur 指向第 m 个节点,也就是需要反转部分的起点
        ListNode cur = start.next;
        ListNode pre = null, next = null;
        // Step2: 反转链表 m 到 n 的部分
        // 循环结束后,pre指向第n个节点,cur指向第n+1个节点
        for (int i = m; i <= n; i++) { // 每次循环变动一次指针指向
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        // Setp3: 调整前后指针
        start.next.next = cur; //将反转的起点的next指向反转的后面一部分。2 -> 5
        start.next = pre;       //将第一步找到的节点指向反转以后的头节点。 1 -> 4
        return dummyHead.next;
    }
}

参考题解:

  击败了100%的java用户

原文地址:https://www.cnblogs.com/HuangYJ/p/14128762.html