Reverse a linked list from positionmton. Do it in-place and in one-pass.

For example:
Given1->2->3->4->5->NULL,m= 2 andn= 4,

return1->4->3->2->5->NULL.

Note:
Givenm,nsatisfy the following condition:
1 ≤m≤n≤ length of list.

    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (m == n) {
            return head;
        }
        ListNode start = null, end = null, dummy = new ListNode(0), temp = dummy;
        dummy.next = head;
        //找到首尾
        for (int i = 0; i <= n; i++) {
            if (i == m - 1) {
                start = temp;
            } else if (i == n) {
                end = temp;
            }
            temp = temp.next;
        }
        ListNode prev = start.next, cur = prev.next;
        while (cur != temp) {
            ListNode now = cur.next;
            cur.next = prev;
            prev = cur;
            cur = now;
        }
        start.next.next = temp;
        start.next = end;
        return dummy.next;
    }

results matching ""

    No results matching ""