您的位置:首页 > 其它

Sort List

2015-09-14 22:49 288 查看
Sort a linked list in O(n log n)
time using constant space complexity.

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* findmid(ListNode* start, ListNode* end)
{
if(start == end)
{
return start;
}
if(start == NULL)
{
return NULL;
}
ListNode* slow = start;
ListNode* fast = start;
ListNode* mid = start;
while(1)
{

if(fast == end)
{
mid = slow;
break;
}
fast = fast -> next;
if(fast == end)
{
mid = slow;
break;
}
slow = slow -> next;
fast = fast -> next;

}

return mid;
}
ListNode* mergeSort(ListNode* start, ListNode* end)
{
if(start == end)
{
return start;
}
if(start == NULL)
{
return NULL;
}
ListNode* mid = findmid(start, end);

ListNode* tmp = mid -> next;

if(mid != NULL)
{
mid -> next = NULL;
}
ListNode* start1 = mergeSort(start, mid);

ListNode* start2 = mergeSort(tmp, end);

ListNode* head = NULL;
ListNode* tail = NULL;
if(start1 == NULL || start2 == NULL)
{
return start1 != NULL ? start1 : start2;
}
while(1)
{

if(start1 -> val < start2 -> val)
{
if(head == NULL)
{
head = start1;
tail = head;
start1 = start1 -> next;
tail -> next = NULL;

}else
{
tail -> next = start1;

start1 = start1 -> next;

tail = tail -> next;

tail -> next = NULL;
}

}else
{
if(head == NULL)
{
head = start2;
tail = head;
start2 = start2 -> next;
tail -> next = NULL;

}else
{

tail -> next = start2;

start2 = start2 -> next;

tail = tail -> next;

tail -> next = NULL;
}
}
if(start1 == NULL || start2 == NULL)
{
if(start1 == NULL)
{
tail -> next = start2;

}
if(start2 == NULL)
{
tail -> next = start1;

}
break;
}
}
return head;
}
ListNode* sortList(ListNode* head)
{
if(head == NULL)
{
return head;
}
ListNode* tail = head;
while(tail -> next != NULL)
{
tail = tail -> next;
}

return mergeSort(head, tail);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: