题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:
利用快慢指针来判断是否有环。为了防止时间太长,我设置了计时器。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
int retry = 100000;
while(fast!= NULL && fast-> next != NULL && fast->next->next != NULL && retry-- > 0){
slow = slow->next;
fast = fast->next;
fast = fast->next;
if(fast == slow){
return true;
}
}
return false;
}
};