题目:
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* sortList(ListNode* head){
if(head==NULL || head->next==NULL)return head;
ListNode *slow = head, *fast = head->next; //一开始是这样的,报错。细思!!!(ListNode* slow = head, fast = head->next;)
while(fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
ListNode* head2 = slow->next;
slow->next = NULL;
ListNode* l = sortList(head);
ListNode* r = sortList(head2);
return merge(l,r);
}
ListNode* merge(ListNode* left, ListNode* right){
ListNode *res = new ListNode(0), *node; //一开始是这样的,报错。细思!!!(ListNode* res(0), node;)
node = res;
while(left && right)
{
if(left->val<=right->val)
{
node->next = left;
node = node->next;
left = left->next;
}
else
{
node->next = right;
node = node->next;
right = right->next;
}
}
if(left)node->next = left;
if(right)node->next = right;
return res->next;
}
};

被折叠的 条评论
为什么被折叠?



