One-loop cpp solution, 4ms


  • 0
    H
    ListNode* reverseBetween(ListNode* head, int m, int n) {
    if (m == n) return head;
    int cnt = 1;
    ListNode *cur = head, *left = NULL, *right = NULL, *pre = NULL;
    while (cnt <= n) {
    	if (m == 1 && cnt == 1) { // case1: m = 1
    		right = cur;
    		pre = right;
    		cur = cur->next;
    		cnt++;
    	}
    	else if (cnt == m - 1 ) {// case2: m > 1
    		left = cur;
    		right = cur->next;
    		pre = right;
    		cur = cur->next;
    		cnt ++;
    	}
    
    	if (cnt > m) { //reverse
    		ListNode* tmp = cur->next;
    		cur->next = pre;
    		pre = cur;
    		cur = tmp;
    		cnt++;
    	}
    	else { // skip
    		cnt++;
    		cur = cur->next;
    	}
    }
    if (m == 1) {
    	head = pre; // head = Node(n)
    }
    else {
    	left->next = pre; // Node(m - 1)->Node(n)
    }
    right->next = cur; // Node(m)->Node(n + 1)
    return head;
    

    }


Log in to reply
 

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