ACCEPTED JAVA solution WITHOUT dummy head, is it good enough?


  • 0
    S
    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            if(head == null || head.next == null || m == n){
                return head;
            }
            ListNode mnode = head; //find m node: the node which rotation will start at
            ListNode mprev = null; // previous node to mnode
            if(m == 1){ //if m== 1 that means rotation node is at beginning of list
                mnode = head;
                mprev = null;
            }
            else{
                for(int i = 1; i < m; i++){
                    mprev = mnode;
                    mnode = mnode.next;
                }
            }
            ListNode nnode = mnode; //n node which is the node that rotation will end at
            ListNode nnext = null;
            for(int i = m; i < n; i++){ //loop to find nnode and the node next to it
                nnode = nnode.next;
                nnext = nnode.next;
            }
            int j = n-m;
            while(j > 0){ //loop to start reversing
                ListNode temp2 = null;
     //if condition to manage head, if mprev is null meaning m starts at head of the list, we need to keep changing head position with every loop
                if(mprev == null){
                    head = mnode.next;
                    temp2 = mnode.next;
                }
                else{ // else head position will not change 
                    mprev.next = mnode.next;
                    temp2 = mprev.next;
                }
                ListNode temp = mnode;            
                nnode.next = temp;
                temp.next = nnext;
                nnext = mnode;
                mnode = temp2;
                
                j--;
            } 
            
            return head;
            
        }
    }

Log in to reply
 

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