concise and clear Java Solution


  • 0

    The solution is to find nodes at position m and n. Then insert the m position node to the next position of n.
    1->2->3->4->5, m = 2, n = 4. set dummy -> 1
    First step: 1->3->4->2->5;
    .....
    Last step: 1->4->3->2->5;
    return dummy.next;

    corner case:
    5->null
    return dummy.next;

    1->2->3->4->5, m = 1, n = 5. set dummy -> 1
    pre = dummy.
    so in the while loop, pre.next will point to 2 at first step.
    The last step dummy will point to the 5.

    public ListNode reverseBetween(ListNode head, int m, int n) {
            if (head == null) {
                return head;
            }
            ListNode mNode = head;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode mpre = dummy;
            ListNode nNode = head;
            int i = 1;
            while (i != m) {
                i++;
                mpre = mNode;
                mNode = mNode.next;
    
            }
            int j = 1;
            while (j != n) {
                j++;
                nNode = nNode.next;
            }
            while (i + 1 <= j) {
                i++;
                ListNode mnext = mNode.next;
                ListNode nnext = nNode.next;
                mpre.next = mnext;
                mNode.next = nnext;
                nNode.next = mNode;
                mNode = mnext;
            }
            return dummy.next;
        }
    

Log in to reply
 

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