Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:定义两个指针,一个每次只走一步,另一个每次走两步。
如果存在环,两个指针迟早会相遇;如果不存在环,则会相继到达终点++NULL。
<span style="color:#333333;">/**
* 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 *p1=head,*p2=head;
if(head==NULL||head->next==NULL) return 0;
</span><span style="color:#990000;"><strong>//判断条件很重要!!需要判断p2->next!=NULL才可以继续判断p2->next->next!=NULL;
//直接判断p2->next->next!=NULL而忽略p2->next!=NULL会出现时间超时错误
//如果没有检测出来p2->next==NULL,直接赋值 p2=p2->next->next是有问题的;</strong></span><span style="color:#333333;">
while(p1->next!=NULL&&<strong>p2->next!=NULL&&p2->next->next!=NULL</strong>){
p1=p1->next;
p2=p2->next->next;
if(p1==p2)return 1;
}
return 0;
}
};</span>