public class LinkedListCycle {
/**
* @param args
*/
public static boolean hasCycle(ListNode head) {
boolean hasCycle=false;
if(head==null||head.next==null){
return hasCycle;
}
ListNode fast=head;
ListNode slow=head;
while(fast.next!=null){
fast=fast.next;
if(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
if(fast==slow){
hasCycle=true;
return hasCycle;
}
}
return hasCycle;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
两个指针,一快一慢,如果有环,满指针会被套圈的、、、
II
v1:
思路:确定有没有环 。当有环是,fast=slow指针,固定其中一个,另一个每次前进一步,再次相遇是走的步数就是环的周长。
head指针每次前进一步,将环循环一遍,与head相遇的节点就是环的入口,及begin节点:代码如下:
package k;
public class LinkedListCycleII {
/**
* @param args
*/
public static ListNode detectCycle(ListNode head) {
ListNode fast=head;
ListNode slow=head;
if(head==null||head.next==null){
return null;
}
while(fast.next!=null){
fast=fast.next;
if(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
if(fast==slow){
int i=0;
while(fast.next!=slow)
{
fast=fast.next;
i++;
}
while(head!=fast){
for(int j=0;j<=i;j++){
if(head==fast)
return head;
else {
fast=fast.next;
}
}
head=head.next;
}
return head;
}
}
return null;
}
}
v2:
思路:找到环,因为fast 是slow 的2倍,所以在环中,slow走不完一圈一定会被fast套圈,,因此slow被fast套圈时不可能走完一圈。
a:head到begin的长度
c:begin到相遇点
q:环的周长
slow走了a+c
fast走了a+nq+c
且fast走了slow 的两倍距离;
nq=a+c;
nq-c=a;
所以slow从相遇点开始走,head从头开始走;
slow走了nq-c步,head走了a步,相遇点就是begin点!!!