In sort Linked List question on leetcode, I am getting runtime error when I initialize fast=head and it is running fine when I initialize fast=head->next. What is the reason behind it? Can anyone explain.
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);
}
};