V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
badgate
V2EX  ›  程序员

leetcode 疑问:运行可以,提交就会报错?

  •  
  •   badgate · 2020-01-11 13:17:41 +08:00 · 2168 次点击
    这是一个创建于 1557 天前的主题,其中的信息可能已经有所发展或是发生改变。
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            if(head==NULL||head->next==NULL) //为什么这里去掉后面对 head->next 的判断提交会报错啊
                return head;
            ListNode* temp=head->next;
            head->next=swapPairs(head->next->next);
            temp->next=head;
            return temp;
        }
    };
    

    错误如下:

     Runtime Error Message: Line 16: Char 29: runtime error: member access within null pointer of type 'struct ListNode' (solution.cpp) 
    

    判断head是空的话,直接return不就行了吗,感觉不用再判断head->next了吧

    4 条回复    2020-01-11 21:57:16 +08:00
    jyyx
        1
    jyyx  
       2020-01-11 13:38:35 +08:00
    head->next=swapPairs(head->next->next);
    jyyx
        2
    jyyx  
       2020-01-11 13:40:34 +08:00
    head->next=swapPairs(head->next->next);
    如果没有上面的保证 null- >next, 这里肯定不行啊
    tyrantZhao
        3
    tyrantZhao  
       2020-01-11 18:22:36 +08:00
    你画个图就知道了,递归最后肯定是最后一个非空节点
    alexsunxl
        4
    alexsunxl  
       2020-01-11 21:57:16 +08:00
    运行的测试集是可以看到的。
    但提交阶段,会有隐藏的测试集, 是很多边界条件的测试。
    没考虑好经常都会这样的。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1300 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:26 · PVG 07:26 · LAX 16:26 · JFK 19:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.