Simple Java Code in one pass and in place with only a dummy head


  • 0
    J

    public ListNode reverseBetween(ListNode head, int m, int n) {

        if (head == null || m == n) {
            return head;
        }
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        
        for (int i = 1; i < m; i++) {
            head = head.next;
        }
        
        ListNode mNode = head.next;
        ListNode nNode = mNode, postnNode = mNode.next;
        
        for (int i = m; i < n; i++) {
            nNode.next = postnNode.next;
            head.next = postnNode;
            postnNode.next = mNode;
            
            mNode = head.next;
            postnNode = nNode.next;
        }
        
        return dummy.next;
    }
    

    Reverse strategy:

    1->2->3->4->5->NULL

    2->1->3->4->5->NULL

    3->2->1->4->5->NULL

    4->3->2->1->5->NULL

    5->4->3->2->1->NULL


Log in to reply
 

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