在排序链接列表问题中,当我初始化 fast=head 时,我收到运行时错误,当我初始化 fast=head->next 时,它运行正常
在 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);
}
};
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);
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论