<p>Given the <code>head</code> of a linked list, return <em>the list after sorting it in <strong>ascending order</strong></em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg" style="width: 450px; height: 194px;" />
<pre>
<strong>Input:</strong> head = [4,2,1,3]
<strong>Output:</strong> [1,2,3,4]
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg" style="width: 550px; height: 184px;" />
<pre>
<strong>Input:</strong> head = [-1,5,3,4,0]
<strong>Output:</strong> [-1,0,3,4,5]
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> head = []
<strong>Output:</strong> []
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the list is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li>
	<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
</ul>

<p>&nbsp;</p>
<p><strong>Follow up:</strong> Can you sort the linked list in <code>O(n logn)</code> time and <code>O(1)</code> memory (i.e. constant space)?</p>

/*
Original solution.
*/

#define HEAD (0)

typedef ListNode Node;

class Solution {
public:
    static bool comparator(Node* a, Node* b){
        /*
        NOTE:
            - We have a comparator to use the in-built sort function.
        */
        return a->val < b->val;
    }

    Node* sortList(Node* head) {
        /*
        NOTE:
            - If the list is empty then we return `NULL`.
        */
        if(!head){
            return NULL;
        }

        /*
        NOTE:
            - Converting a conventional list to a vector array so that we can 
            sort it using an implementation of mergesort. 
        */
        vector<Node*> converted;
        this->getList(head, converted);

        sort(converted.begin(), converted.end(), this->comparator);

        /*
        NOTE:
            - Reattaching the list. 
        */
        for(int i = 0, j = 1; j < converted.size(); i++, j++){
            converted[i]->next = converted[j];
        }
        converted[converted.size() - 1]->next = NULL;

        return converted[HEAD];
    }

    void getList(Node* head, vector<Node*>& list){
        /*
        NOTE:
            - Recursive function to get a conventional singly linked and convert
            it to an array. Technically not converting, just modifying the empty
            array passed into it.
        */
        if(!head){
            return;
        }

        list.push_back(head);

        getList(head->next, list);
    }
};
70091