## Question

Sort a linked list in $O(n log n)$ time using constant space complexity.

## Solution

Result: Accepted Time: 16 ms

Here should be some explanations.

/**
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/

struct ListNode * get_tail(struct ListNode * head)
{
}
#define INC_ORDER 1
#define DEC_ORDER 2
#define NO_ORDER 0
{
int ans = 3,tmp;
{
if(last > tmp) // DEC not INC
ans &= DEC_ORDER;
if(last < tmp) // INC not DEC
ans &= INC_ORDER;
last = tmp;
}
return ans;
}

struct ListNode * reverse(struct ListNode* head)
{
{
}
}
{

else if(ord == DEC_ORDER)
struct ListNode low, up,mid;
struct ListNode * llast = &low, *ulast = &up,*mlast=head;
struct ListNode **tmp = NULL;
bool inc = true,dec = true;
int value = mlast->val;
{
tmp = head->val < value ? (&llast):(&ulast);
tmp = &mlast;
}
llast->next = NULL;
ulast->next = NULL;
mlast->next = up.next;
if(low.next)
{
get_tail(low.next)->next = mid.next;
return low.next;
}
return mid.next;
}
struct ListNode* sortList(struct ListNode* head) {

• Time Complexity: $O(n*log(n))$
• Space Complexity: $O(log(n))$