admin 管理员组文章数量: 1184232
今天在LeetCode上做一道求单链表交集的算法题(160),提交时出现如下错误:
提交的代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/<pre name="code" class="cpp">/*双指针求单链表交集*/<pre name="code" class="cpp">struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *pA=headA,*pB=headB;
int la,lb,n=0;
if(pA==NULL||pB==NULL)
return NULL;
while(pA)
{
la++;
pA=pA->next;
}
while(pB)
{
lb++;
pB=pB->next;
}
if(la<=lb)
{
n=lb-la;
pA=headA;
pB=headB;
while(n)
{
pB=pB->next;
n--;
}
}
else
{
n=la-lb;
pA=headA;
pB=headB;
while(n)
{
pA=pA->next;
n--;
}
}
while(pA!=pB)
{
pA=pA->next;
pB=pB->next;
}
return pA;
}
仔细找了半天也没发现程序逻辑上的错误,令我百思不得其解,于是开始研究Runtime Error这个问题,在
上找到了如下定义:
(run´tīm er´&r) (n.) An error that occurs during the execution of a . In contrast, compile-time errors occur while a program is being . Runtime errors indicate in the program or problems that the designers had anticipated but could do nothing about. For example, running out of will often cause a runtime error.
Note that runtime errors differ from or in that you can often recover gracefully from a runtime error.
大致翻译如下:Rumtime error(运行时错误)是发生在程序运行过程中的一种错误。与之相对的是compile-time errors(编译时错误),它发生在程序编译过程中。Runtime errors表明程序中存在一些漏洞和问题,而程序员虽然能预料到这些错误但并不能做任何事情。比如说,内存溢出通常会导致runtime error。
应当注意的是runtime errors和bombs或者crashes(程序崩溃)不同,你通常可以从前者中优雅地恢复过来。
另外在C++中查到了run_time这个类( ):
可以看到有四种错误会导致runtime_error,具体可以点击上述链接进行查看。
知道了runtime error机理后回到我的程序,最后发现是变量初始化的问题:
struct ListNode *pA=headA,*pB=headB;
int la,lb,n=0;
本来希望将la,lb,n都初始化为0,但上述代码实际上只声明了la和lb,并没有对其进行初始化,所以运行时其值是一个随机数,从而导致程序错误。
将上述代码改为:
struct ListNode *pA=headA,*pB=headB;
int la=0,lb=0,n=0;
提交通过。
版权声明:本文标题:LeetCode新手指南:与Runtime Error的英勇对战 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1770689406a3536491.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论