My 0ms C++ Solution


  • 0
    S
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            if (m == n) return head;
            
            ListNode *fakeHead = new ListNode(0);
            fakeHead->next = head;
            ListNode *preReverse = fakeHead, *postReverse, *reverseTail, *reverseHead;
            int index = 1;
            
            for (; index < m; index++) {
                preReverse = preReverse->next;
                if (preReverse == NULL) return NULL;
            }
            reverseHead = preReverse->next;
            reverseTail = reverseHead;
            postReverse = reverseTail->next;
            
            for (index++; index < n+1; index++) {
                ListNode *tmp = postReverse;
                postReverse = postReverse->next;
                tmp->next = reverseHead;
                reverseHead = tmp;
            }
            
            reverseTail->next = postReverse;
            preReverse->next = reverseHead;
            
            return fakeHead->next;
        }
    };

Log in to reply
 

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