题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
bool hasCycle(struct ListNode* head ) {
// write code here
struct ListNode *pslow = head, *pfast = head; //数学规律,快的走两步,慢的走一步,如果回环则始终会追上
while(pfast && pfast->next && pfast->next->next){ //注意,由于下面需要使用到pfast的next 和 next->next,因此需要判断是否存在
pfast = pfast->next->next;
pslow = pslow->next;
if(pfast->val == pslow->val)
return true;
}
return false;
}