[C++] iterative, in-place (space in (1)), runtime in (n), optimal (?)


  • 0
    4
     ListNode * reverseList( ListNode * head )
        {
            if( !head || !head->next ) return head;
            
            ListNode * t1 = head;
            head = t1->next;
            ListNode * t2 = head->next;
            
            t1->next = 0;
            head->next = t1;
    
            while( t2 )
            {
                t1 = t2->next;
                t2->next = head;
                head = t2;
                t2 = t1;
            }
            return head;
        }

Log in to reply
 

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