题目:
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) { if(head ==NULL) return false; int count =10000; ListNode*slow=head; ListNode*fast=head; do { if(slow==NULL) return false; else slow=slow->next; if(fast->next==NULL||fast->next->next==NULL) return false; else fast=fast->next->next; if(slow==fast) { return true; } else { count--; } if(count==0) return false; }while(true); } };