Total Accepted: 96475
Total Submissions: 261646
Difficulty: Medium
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
Hide Similar Problems
思路:
使用一个快指针fast和一个慢指针slow,快指针的速度是慢指针的2倍。
如果fast指针能追上慢指针slow,还代表有环存在。
因为两个指针的速度相差1,所以有环的话一定可以追上。
code:
/**
* 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;
ListNode *fast,*slow;
fast=head;slow=head;
while(slow && fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow) return true;
}
return false;
}
};