Sharing my 80ms C++ solution


  • 0
    T
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
     
    class Solution {
    public:
        ListNode* insertionSortList(ListNode* head) {
            if(head==NULL || head->next==NULL)
                return head;
            ListNode* headOfRest = insertionSortList(head->next);
            if(head->val <= headOfRest->val)
            {
                head->next = headOfRest;
                return head;
            }
            else
            {
                ListNode* p = headOfRest;
                while(p->next && p->next->val < head->val)
                {
                    p = p->next;
                }
                
                head->next = p->next;
                p->next = head;
                return headOfRest;
            }
        }
    };

Log in to reply
 

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