Simple Java Solution, Time O(n), Space O(1)


  • 1
    H
    public ListNode reverseBetween(ListNode head, int m, int n) {
            if(head == null || m < 1|| n <= m){
                return head;
            }
            
            ListNode dummyHead = new ListNode(0);
            dummyHead.next = head;
            ListNode sublistHead = dummyHead;
            
            int k = 1;
            while(k++ < m){
                sublistHead = sublistHead.next;
            }
            
            //Reverse Sublist
            ListNode sublistIter = sublistHead.next;
            while(m++ < n){
                ListNode temp = sublistIter.next;
                sublistIter.next = temp.next;
                temp.next = sublistHead.next;
                sublistHead.next = temp;
            }
            
            return dummyHead.next;
            
        }
    

Log in to reply
 

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