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

2020-01-11 13:17:41 +08:00
 badgate
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了吧

2190 次点击
所在节点    程序员
4 条回复
jyyx
2020-01-11 13:38:35 +08:00
head->next=swapPairs(head->next->next);
jyyx
2020-01-11 13:40:34 +08:00
head->next=swapPairs(head->next->next);
如果没有上面的保证 null- >next, 这里肯定不行啊
tyrantZhao
2020-01-11 18:22:36 +08:00
你画个图就知道了,递归最后肯定是最后一个非空节点
alexsunxl
2020-01-11 21:57:16 +08:00
运行的测试集是可以看到的。
但提交阶段,会有隐藏的测试集, 是很多边界条件的测试。
没考虑好经常都会这样的。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/637063

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX