Straight forward solution. Easy to understand


  • 0
    public ListNode reverseBetween(ListNode head, int m, int n) {
            ListNode fakeHead = new ListNode(0);
            fakeHead.next = head;
            ListNode start = fakeHead;
            
            //move to the start point
            int count = m;
            while(head != null && --count > 0){
                head = head.next;
                start = start.next;
            }
            
            ListNode revHead = null;
            
            // reverse the list
            count = n - m;
            while(head != null && count >= 0){
                ListNode next = head.next;
                head.next = revHead;
                revHead = head;
                head = next;
                count --;
            }
            
            // reconnect to the rest part
            start.next.next = head;
            start.next = revHead;
            
            return fakeHead.next;
        }
    

Log in to reply
 

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