Duk*_*s17 8 c++ linked-list data-structures
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;
}
};
Run Code Online (Sandbox Code Playgroud)
我正在练习一个看起来很简单的面试代码.我必须返回一个bool来确定单链表是否有循环.我做了两个指针步行者,它移动了1步和每次迭代移动2步的跑步者.
但是这段代码给了我一个错误:
Line 15: member access within null pointer of type 'struct ListNode'
Run Code Online (Sandbox Code Playgroud)
是什么原因导致错误?