[英]Runtime error while merging two sorted linked list
I am writing a c++ code to merge two sorted link lists.I am using two pointer method.I am getting a runtime error for the code below.I am unable to debug the code.我正在编写一个 c++ 代码来合并两个排序的链接列表。我正在使用两个指针方法。下面的代码出现运行时错误。我无法调试代码。
Error- Your submission stopped because of a runtime error.错误 - 您的提交因运行时错误而停止。 ex: division by zero, array index out of bounds, uncaught exception.
例如:除以零、数组索引超出范围、未捕获的异常。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::mergeTwoLists(ListNode* A, ListNode* B) {
ListNode* head1=new ListNode(-1);
head1->next=A;
ListNode* head2=new ListNode(-1);
head2->next=B;
ListNode* temp1=head1;
ListNode* temp2=head2;
while(temp1->next!=NULL || temp2->next!=NULL)
{
if(temp1->next->val <= temp2->next->oval)
{
// if(temp1->next==NULL) break;
//else
temp1=temp1->next;
}
else if(temp1->next->val > temp2->next->oval)
{
ListNode* temp=temp1->next;
ListNode* t2=temp2->next->next;
temp1->next=temp2->next;
temp2->next=t2;
temp1->next->next=temp;
temp1=temp1->next;
}
}
if(temp1->next==NULL)
{
temp1->next=temp2->next;
temp2->next=NULL;
}
return head1->next;
}
This condition:这个条件:
while(temp1->next!=NULL || temp2->next!=NULL)
is incorrect, since you will be accessing invalid memory if exactly one of these pointers is NULL
.是不正确的,因为如果这些指针之一恰好是 NULL ,您将访问无效的
NULL
。
Instead, you need to do:相反,您需要执行以下操作:
while(temp1->next!=NULL && temp2->next!=NULL)
Also, you should use nullptr
instead of NULL
.此外,您应该使用
nullptr
而不是NULL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.