A lazy method for this problem


  • -37
    E

    Firstly, create a vector (C++ standard) with the content of the list;

    Secondly, sort the vector;

    Finally, return a list with the content of the sorted vector.

    It's very easy to implement since you can sort the vector with C++ standard function "sort".

    ListNode * creatList(vector<int> A)
    {
        ListNode * head = new ListNode(A[0]);
        ListNode * tail = head;
    
        for(size_t i=1; i<A.size(); ++i)
        {
            ListNode * temp = new ListNode(A[i]);
            tail -> next = temp;
            tail = temp;
        }
    
        return head;
    }
    
    ListNode *sortList(ListNode *head) {
    
        if(head == NULL || head -> next == NULL)
            return head;
    
        vector<int> vlist;
        while(head != NULL)
        {
            vlist.push_back(head -> val);
            head = head -> next;
        }
    
        sort(vlist.begin(), vlist.end());
    
        ListNode *h = creatList(vlist);
    
        return h;
    }

  • 4
    S

    Note that the question explicitly asks for "constant space complexity". In a real interview, this answer would dramatically decrease your chance of being hired.


  • 0
    E

    Ok, thank you, I'll think about it seriously then.


Log in to reply
 

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