C++ recursive insertion sort.


  • 4
    C
    ListNode* insertionSortList(ListNode* head) {
        if (head == nullptr || head->next == NULL)
            return head;
        ListNode *h = insertionSortList(head->next);
        if (head->val <= h->val) {  // first case
            head->next = h;
            return head;
        }
        ListNode *node = h;   // second case
        while (node->next && head->val > node->next->val)
            node = node->next;
        head->next = node->next;
        node->next = head;
        return h;
    }

Log in to reply
 

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