Java Easy to Understand Solution


  • 0
    S
    public ListNode reverseBetween(ListNode head, int m, int n) {
            if(head==null || head.next==null)
                return head;
            ListNode ptr=head;
            ListNode ptrPrev = null;
            ListNode revHead=null;
            for(int i=1;i<m;i++) {
                ptrPrev = ptr;
                ptr=ptr.next;
            }
            if(ptr!=null && m!=n) {
               revHead = reverseHelper(ptr, n-m); 
               if(ptrPrev!=null)
                    ptrPrev.next=revHead;
                else
                    head=revHead;
            }
            
            return head;
        }
        
        public ListNode reverseHelper(ListNode ptr, int numOfSwaps) {
            if(ptr==null || ptr.next==null)
                return null;
            ListNode curr=ptr;
            ListNode prev = null;
            ListNode nxt;
            int count=0;
            
            while(curr!=null && count!=numOfSwaps+1) {
                nxt = curr.next;
                curr.next=prev;
                prev=curr;
                curr=nxt;
                count++;
            }
            ptr.next=curr; // to connect reversed list with the remaining part of the list.
            return prev;
        }
    
    

Log in to reply
 

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