C++ recursive solution.


  • 1
    D
    class Solution 
    {
    
    public:
        ListNode* reverseList(ListNode* head) 
        {
            if(!head)
                return NULL;
            
            if(!head->next)
            {
                // Reached the last node in the original list.
                // Just return it.
                return head;
            }
            
            // Reverse the rest of the list.
            ListNode* rev = reverseList(head->next);
            
            // head->next is the tail/last element in 
            // the reversed list.
            ListNode* tail = head->next;
            
            // We make the tail point to head, this
            // way head becomes the new tail in the reversed list.
            tail->next = head;
            
            // And end the reveresed list with NULL.
            head->next = NULL;
            
            return rev;
        }
    };
    

Log in to reply
 

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