1.題目
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
給一個連結清單,判斷是否有環
2.分析
關于是否成環的判斷在Happy Number這題就已經用到過floyd cycle detection algorithm
兩個指針slow每次走1步,fast每次走2(or more)步。如果存在cycle,那麼slow和fast必定在某點相遇。
3.代碼
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL || head->next == NULL)
return false;
ListNode* slow = head;
ListNode* fast = head;
while(slow&&fast&&fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
};