Java solution, intuitive and easily understandable


  • 0

    Hello everyone,

    I present you, very easy to understand solution in Java.

     public ListNode reverseBetween(ListNode head, int m, int n) {
            if(head == null || head.next == null || m == n)
                return head;
            
            ListNode dummy = new ListNode(-1), mNode = head, nNode = head, prevmNode = dummy, postnNode = null;
            dummy.next = head;
            
            // move N node
            for(int i = 0; i < n - 1; i++){
                nNode = nNode.next;
            }
            postnNode = nNode.next;
            
            // move M node
            for(int i = 0; i < m - 1; i++){
                prevmNode = mNode;
                mNode = mNode.next;
            }
            
            // reverse
            ListNode curr = mNode, prev = postnNode, temp = null;
            while(curr != postnNode){
                temp = curr.next;
                curr.next = prev;
                prev = curr;
                curr = temp;
            }
            
            prevmNode.next = nNode;
            
            return dummy.next;
        }
    

Log in to reply
 

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