My recursive cpp code


  • 1
    C
    class Solution {
    public:
        ListNode* insertionSortList(ListNode* head) 
        {
            if(!head) return head;
            
            ListNode* sortedList = insertionSortList(head->next);
            
            ListNode fake(0);
            ListNode* ptr = &fake;
            ptr->next = sortedList;
            
            while(ptr->next)
            {
                if(head->val <= ptr->next->val)
                {
                    ListNode* tmp = ptr->next;
                    ptr->next = head;
                    head->next = tmp;
                    break;
                }
                ptr = ptr->next;
            }
            
            if(!ptr->next)
            {
                ptr->next = head;
                head->next = NULL;
            }
            
            return fake.next;
        }
    };

Log in to reply
 

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