Regardless the space constrains, it can be solved recursively. Similarly with create BST from a sorted list, it can go by in-order. Solving it in iteration will be tedious.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode *merge(ListNode*l1, ListNode *l2)
{
ListNode head(0);
ListNode *p = &head;
while(l1 && l2)
{
if(l1->val < l2->val)
{
p->next = l1;
l1 = l1->next;
}
else
{
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
if(l2) p->next = l2;
else p->next = l1;
return head.next;
}
ListNode *sortList(ListNode* & head, int start, int end)
{
if(start == end)
{
ListNode *p = head;
//Note, move head to next for the next recursive call
head = head->next;
p->next = NULL;
return p;
}
int mid = start + (end-start)/2;
return merge(sortList(head, start, mid),
sortList(head, mid+1, end));
}
public:
ListNode *sortList(ListNode* head)
{
if(!head) return head;
ListNode *p = head;
int c = 0;
while(p->next)
{
c++;
p = p->next;
}
return sortList(head, 0, c);
}
};