My working solution -- any improvements you can point out ?


  • 0
    K
    ListNode * reverseBetween(ListNode* head, int m, int n) {
    	if (m == n) return head;
    	
    	ListNode *prevNode = NULL;
    	ListNode *currentNode = head;
    
        // until we reach m just keep going
    	for (int i = 1; i < m; ++i) {
    		prevNode = currentNode;
    		currentNode = currentNode->next;
    	}
    
        // at m record change over and advance one
    	ListNode *startNode = prevNode;
    	ListNode *endNode = currentNode;
    	prevNode = currentNode;
    	currentNode = currentNode->next;
    	
        // from m to n 
    	ListNode *nextNode = NULL;
    	for (int j = m; j < n; ++j) {
    		nextNode = currentNode->next;
    		currentNode->next = prevNode;
    		prevNode = currentNode;
    		currentNode = nextNode;
    	}
        
        // reattach and take care of edge case
    	if (startNode) {
    		startNode->next = prevNode;
    	} else {
    		head = prevNode;
    	}
    	endNode->next = currentNode;
    	return head;
    }

Log in to reply
 

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