My simple java solution


  • 0
    H
    public ListNode reverseBetween(ListNode head, int m, int n) {
    	ListNode dummy = new ListNode(0), oldTail = dummy, newTail = head, newHead = null;
    	dummy.next = head;
    	
    	for (int i = 1; i <= n; i++) {
    	    if (i < m) {
    	        oldTail = oldTail.next;
    	        head = head.next;
    	        newTail = head;
    	    }
    	    else {
    	        ListNode cur = head;
                head = head.next;
                cur.next = newHead;
                newHead = cur;
    	    }
    	}
        
        oldTail.next = newHead;
        if (newTail != null) newTail.next = head;
        
        return dummy.next;
    }

Log in to reply
 

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