My C++ O(n^2) solution


  • 0
    M
    class Solution {
    public:
        ListNode* insertionSortList(ListNode* head) {
            ListNode dummy(0);
            
            while (head != nullptr) {
                ListNode *next_head = head->next;
                ListNode *it = &dummy;
                while (it->next && it->next->val < head->val) {
                    it = it->next;
                }
                head->next = it->next;
                it->next = head;
                head = next_head;
            }
            
            return dummy.next;
        }
    };

Log in to reply
 

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