C++ O(n) (6ms) In-Place One-pass Two-pointers Iterative Solution with Explanations


  • 0

    The image below demonstrates the operation performed in the very first iteration.
    Demonstration of the very first iteration

        //Iterative solution
        ListNode* iterative(ListNode* head) {
            if (head == NULL)
                return NULL;
            ListNode* curr = head;    ------ Step 1 ------
            ListNode* prev = NULL; 
            ListNode* temp = NULL;        
            while (curr != NULL) {
                temp = curr->next;    -------End Step 1------
                curr->next = prev;        ------ Step 2 --------
                prev = curr;                -------Step 3 ------
                curr = temp;                ------ End Step 3-------
            }
            return prev;
        }
    

Log in to reply
 

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