在有关 leetcode 的排序链接列表问题中,当我初始化 fast=head 时出现运行时错误,而当我初始化 fast=head->next 时它运行良好。背后的原因是什么?谁能解释一下。
class Solution {
public:
ListNode* merge(ListNode* p, ListNode* q)
{
ListNode* dummy = new ListNode(0);
ListNode* t = dummy;
while(p && q)
{
if(p->val < q->val)
{
t->next = p;
p = p->next;
}
else
{
t->next = q;
q = q->next;
}
t = t->next;
}
t->next = (p) ? p : q;
return dummy->next;
}
ListNode* sortList(ListNode* head)
{
if(!head || !head->next)
return head;
ListNode *slow=head, *fast=head; //I am talking about this
while(fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
ListNode* head2 = slow->next;
slow->next = NULL;
ListNode* left = sortList(head);
ListNode* right = sortList(head2);
return merge(left, right);
}
};