C++ 'struct ListNode' 类型的空指针内的成员访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44734028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
member access within null pointer of type 'struct ListNode'
提问by Dukakus17
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL) return false;
ListNode* walker = head;
ListNode* runner = head;
while(runner->next != NULL && walker->next != NULL){
walker = walker->next;
runner = runner->next->next;
if(walker == runner) return true;
}
return false;
}
};
I was practicing an interview code which seemed to be pretty simple. I have to return a bool that determines whether or not the singly-linked list has a cycle. I made two pointers walker which moves 1 step and runner which moves 2 steps every iteration.
我正在练习一个看起来很简单的面试代码。我必须返回一个 bool 来确定单向链表是否有循环。我制作了两个指针步行器,每次迭代移动 1 步,跑步者移动 2 步。
But then this code gave me an error:
但是后来这段代码给了我一个错误:
Line 15: member access within null pointer of type 'struct ListNode'
What causes that error?
是什么导致了这个错误?
采纳答案by user7860670
You only make sure that runner->next
is not null, however after assignment
您只需要确保它runner->next
不为空,但是在分配之后
runner = runner->next->next;
runner = runner->next->next;
runner
can become null.
runner
可以变为空。