The java solution

  • 2

    Go through the list to construct a pointer array of size (n-m+1) to keep the pointers from nth element to mth element. Then operate on this array to swap the elements symmetric to the center. For example, swap mth with nth, then (m+1)th with (n+1)th.

     public ListNode reverseBetween(ListNode head, int m, int n) {
            // back up head
            ListNode headBak = head;
            // get pointer array to point to all the elements betweent the mth and the nth elements
            ListNode[] pointers = new ListNode[n-m+1];
            int i = 0;
            while (head != null){
                if(i >= m){
                    pointers[i-m] = head;
                if (i == n){
                head =;
            // between mth and nth element, swap start/end and move pointer towards center
            int len = pointers.length;
            for(int j = 0; j < len/2; j++){
                int temp = pointers[j].val;
                pointers[j].val = pointers[len-1-j].val;
                pointers[len-1-j].val = temp;
            return headBak;

Log in to reply

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