Simple Java solution 0 ms


  • 0
    R
    public ListNode reverseBetween(ListNode head, int m, int n) {
            ListNode ptr = head;
            ListNode prevFirst = null;
            int i =m;
            while(m>1) {
                prevFirst = ptr;
                ptr = ptr.next;
                m-=1;
            }
            ListNode last = ptr;
            ListNode prev = ptr;
            ListNode curr = ptr;
            ListNode temp = ptr.next;
    
            while(i<n) {
                curr = temp;
                temp = temp.next;
                curr.next =prev;
                prev = curr;
                i+=1;
            }
            last.next = temp;
            if(prevFirst==null) return curr;
            prevFirst.next = curr;
            return head;
        }
    

Log in to reply
 

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