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