题目
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断给定的链表中是否存在环
- 思路
设置一个慢指针和一个快指针,每次令快指针走两步,慢指针走一步。如果存在环,则快指针必定在某一刻会超过慢指针正好一圈,即正好和慢指针相遇。
- 程序(C++)
class Solution{
public:
bool hasCycle(ListNode* head){
if(head==NULL||head->next==NULL) return false;
ListNode* slow=head;
ListNode* fast=head->next;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
if(fast!=slow)
{
fast=fast->next->next;
slow=slow->next;
}
else return true;
}
return false;
}
};
离bug free还差一步:
漏掉了head->next==NULL的情况。
- 程序(java)
public class Solution{
public boolean hasCycle(ListNode head){
if(head==null||head.next==null) return false;
ListNode slow=head;
ListNode fast=head.next;
while(fast.next!=null&&fast.next.next!=null)
{
if(fast!=slow)
{
fast=fast.next.next;
slow=slow.next;
}
else return true;
}
return false;
}
}