[java/0ms] easy & self-explanatory with dummy node.


  • 0
    
    public ListNode reverseBetween(ListNode head, int m, int n) {
            if (head == null || m == n)
                return head;
                
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            // find the previous node of m_th node
            ListNode pre = dummy, cur = head;
            int tmp = m;
            while (cur != null && --tmp > 0) {
                pre = pre.next;
                cur = cur.next;
            }
            
            // if the length of the list is smaller than m
            if (cur == null) {
                dummy.next = null;
                return head;
            }
            
            // find the node after n_th node.
            tmp = m;
            while (tmp++ <= n && cur != null) {
                cur = cur.next;
            }
            ListNode end = cur;
            
            // reverse the nodes from m to n
            ListNode kur = end;
            cur = pre.next;
            while (cur != end) {
                ListNode temp = kur;
                kur = cur;
                cur = cur.next;
                kur.next = temp;
            }
            cur = kur;
            pre.next = cur;
            
            pre = dummy.next;
            dummy.next = null;
            
            return pre;
        }
    
    

Log in to reply
 

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