“`
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
“
算法的思想很简单,定义两个指针,一个每次前进一步,一个每次前进两步。如果在它们前进到下一个节点为NULL之前它们的值相等,表示能找到环,否则不能,注意需要对输入为空进行判断,以及对链表进行处理时需要对每个指针的next元素进行判断。
runtime:12ms
`/**
* 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 * slow=head;
ListNode * fast=head;
//注意这里需要三个判断条件
while(slow->next!=NULL&&fast->next!=NULL&&fast->next->next!=NULL)
{
//不要写成slow+1,fast+2了
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
return true;
}
return false;
}
};