C++ solution, easy to understand


  • 0
    I

    The idea is to reverse the list from m to n and reconnect three parts.

    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode *dummy = new ListNode(0), *cur = dummy, *prev = NULL, *first = NULL, *last = NULL;
        dummy->next = head;
        for (int i = 0; i <= n; i++) {
            if (i == m - 1) {
                first = cur;
                cur = cur->next;
            } else if (i > m - 1) {
                if (i == n) last = cur;
                ListNode *temp = cur;
                cur = cur->next;
                temp->next = prev;
                prev = temp;
            } else {
                cur = cur->next;
            }
        }
        first->next->next = cur;
        first->next = last;
        return dummy->next;
    }

Log in to reply
 

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