92. Reverse Linked List II

这道题是把LinkedList里面的一段翻转。
因为翻转之后head 不确定,所以这里用dummy head来简化逻辑。
1 -> 2 -> 3 -> 4 -> 5 变成 1 -> 4 -> 3 -> 2 ->5
先弄一个0, 变成 0 ->1 -> 2 -> 3 -> 4 -> 5
然后走到1的位置, 把后面三个翻转,
再把 1 -> 4, 把 2 -> 5

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode node = dummy;
        int count = 1;
        // find m
        while (count < m) {
            node = node.next;
            count++;
        }
        // reverse m to n
        reverse(node, n - m + 1);
        return dummy.next;
    }
    private void reverse(ListNode head, int k) {
        // 1 -> 2 -> 3 -> 4 -> 5
        // 1,  2,3,4  4 3 2
        ListNode prev = null;
        ListNode node = head.next;
        for (int i = 0; i < k; i++) {
            ListNode next = node.next;
            node.next = prev;
            prev = node;
            node = next;
        }
        head.next.next = node; // connect 2 -> 5
        head.next = prev; // connect 1 -> 4
        return;
    }
}

你可能感兴趣的:(92. Reverse Linked List II)