141. Linked List Cycle
判断Linked List是否是循环List
Solution:
用快慢指标来做
如果是循环List,总会有两者一样的一天
反之则会有人先变成nullptr
可以参考:https://hackmd.io/@Hsins/fast-slow-pointers
Code:
class Solution
{
public:
bool hasCycle(ListNode *head)
{
if(!head || !head->next)
return false;
ListNode* slow = head;
ListNode* fast = head->next;
while(slow != fast)
{
if(!fast || !fast->next)
return false;
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};