public class Link {
static class Node
{
int val;
Node next;
public Node(int val)
{
this.val=val;
}
}
static boolean isLinkedListContainsLoop(Node head){
if(head==null){
return false;
}
Node slowPtr=head;
Node fastPtr=head;
while(slowPtr.next!=null && fastPtr.next.next!=null){
slowPtr=slowPtr.next;
fastPtr=fastPtr.next.next;
if(slowPtr==fastPtr){
return true;
}
}
return false;
}
public static void main(String[] args) {
Node n1=new Node(1);
Node n2=new Node(2);
Node n3=new Node(3);
Node n4=new Node(4);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n3;
System.out.println(isLinkedListContainsLoop(n1));
}
}
当fast按照每次2步,slow每次一步的方式走,发现fastPtr和slowPtr重合,确定了单向链表有环路。