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;
}
};