Concise solution in C++


  • 2
    S
    class Solution {
    public:
        ListNode *insertionSortList(ListNode *head) {
            
            if(head == NULL || head->next == NULL)
                return head;
                
            ListNode dummy(INT_MIN);
            dummy.next = head;
            head = &dummy;
            
            ListNode *p = head->next;
            head->next = NULL;
            
            while(p)
            {
                ListNode *nextP = p->next;
                p->next = NULL;
                
                ListNode *pre = head;
                while(pre->next && pre->next->val <= p->val)
                    pre = pre->next;
                
                p->next = pre->next;
                pre->next = p;
                
                p = nextP;
            }
            
            return head->next;
        }
    };

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


Log in to reply
 

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