148. Sort List
题目
Sort a linked list in O(n log n) time using constant space complexity.
解答Accept
- 实现之前看了思路,想想先就用递归实现
- 结果模仿别人写都有5个bug,感觉没有用心啊!!!
// Definition for singly - linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// sort list
class Solution {
public:
ListNode* findMiddle(ListNode* head)
{
ListNode* slow = head;
ListNode* fast = head->next;
while (fast&&fast->next) //bug1 ||
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* MergeList(ListNode* left, ListNode*right)
{
if (left==NULL)
{
return right;
}
if (right==NULL)
{
return left;
}
ListNode* temp = new ListNode(0);
ListNode* temp_head = temp; //bug2 头指针移动
while (left&&right)
{
if (left->val<right->val)
{
temp->next = left; //bug3 顺序反了
left = left->next;
}
else
{
temp->next = right;
right = right->next;
}
temp = temp->next;
}
if (left) //bug4 if->while
{
temp->next = left;
}
if (right)
{
temp->next = right;
}
return temp_head->next;
}
ListNode* sortList(ListNode* head) {
if (!head||!head->next) // Line 57: member access within null pointer of type 'struct ListNode'
{
return head; //bug5 忘记取!
}
ListNode *middle = findMiddle(head);
ListNode* left=sortList(middle->next);
middle->next = NULL;
ListNode* right = sortList(head);
ListNode *ret=MergeList(left, right);
return ret;
}
};