Java in-place one-pass solution.


  • 1
    C
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || head.next == null || m == n) {
            return head;
        }
        ListNode pre, dummy = new ListNode(0);
        pre = dummy;
        dummy.next = head;
        for (int i = 0; i < m-1; i++) {
            pre = pre.next;
        }
        ListNode cur = pre.next, p = pre.next, node = null;
        for (int i = 0; i <= n-m; i++) {
            ListNode nxt = cur.next;
            cur.next = node;
            node = cur;
            cur = nxt;
        }
        p.next = cur;
        pre.next = node;
        return dummy.next;
    }

  • 0
    J

    I think this is two-pass solution:)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.