C++ one-pass solution.


  • -1
    C
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode *dummy = new ListNode(0), *node;
        dummy->next = head;
        node = dummy;
        for (int i = 0; i < m-1; i++)
            node = node->next;
        ListNode *h = node->next, *cur;
        cur = h;
        ListNode *end = NULL;
        for (int i = 0; i < n-m+1; i++) {
            ListNode *nxt = cur->next;
            cur->next = end;
            end = cur;
            cur = nxt;
        }
        h->next = cur;
        node->next = end;
        ListNode *tmp = dummy->next;
        delete dummy;
        return tmp;
    }

Log in to reply
 

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