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;
提交通过。

本文标签: 故事 的是 编程