My java solution only need a few number of extra space


  • 0
    Y
    public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null||head.next==null||m<=0||m>=n) return head;
        int i;
        ListNode idx,tem,reverseTail,reverseHead;
        reverseHead=new ListNode(100);
        reverseTail = new ListNode(100);
        if(m==1){
            reverseHead.next=reverseTail;
            idx=head;
            i=0;
        }else{
            i=1;
            tem=head;
            while(i<m-1){
                tem=tem.next;
                i++;
            }
            idx=tem.next;
            reverseHead=tem;
            reverseHead.next=reverseTail;
        }
        while(i<n&&idx!=null){
            i++;
            tem=idx;
            idx=idx.next;
            tem.next=reverseHead.next;
            reverseHead.next=tem;
            if(i==m) reverseTail=tem;
        }
        reverseTail.next=idx;
        if(m==1) return reverseHead.next;
        return head;
    }
    

    }


Log in to reply
 

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