public static Boolean isHasCircle( LinkListNode head )
{
if(head==null) return null;
LinkListNode fast=head;
LinkListNode slow=head;
Boolean flag = false;
while(fast!=null && fast.next!=null )
{
fast = fast.next.next;
slow = slow.next;
if(fast == slow)
{
flag = true;
break;
}
}
return flag;
}
public static int lengthCircleOfList(LinkListNode head)
{
if(head==null) return -1;
int count=0;
LinkListNode fast = head;
LinkListNode slow = head;
boolean flag =false;
int sum = 2; //判断是否为第二次相遇
while(fast!=null && fast.next!=null)
{
fast = fast.next.next;
slow = slow.next;
if(fast == slow)
{
flag = true;
sum--;
}
if(sum == 0)break;
if(flag)
{
count++;
}
}
return count;
} public static LinkListNode theEnterOfList(LinkListNode head)
{
if(head==null) return null;
LinkListNode fast = head;
LinkListNode slow = head;
while(fast!=null && fast.next!=null)
{
fast = fast.next.next;
slow = slow.next;
if(slow == fast)
{
break;
}
}
fast = head; //将快指针放到链头
while(slow!=null && fast!=slow) //相遇时跳出,此节点便是入口
{
fast=fast.next;
slow = slow.next;
}
return slow;
} public static boolean isIntersect(LinkListNode head1,LinkListNode head2)
{
//将第2个链表尾插到第1个链表末尾
LinkListNode p =head1;
while(p.next!=null)
{
p=p.next;
}
p.next = head2;
// LinkListNode temp = theEnterOfList(head1); //第一个公共节点
// System.out.println(temp.value);
return isHasCircle(head1);
}版权声明:本文为博主原创文章,转载请注明出处。
原文:http://blog.csdn.net/u014307117/article/details/47761237