1、判断链表是否有环
设置快慢指针,快指针每次走两步,慢指针每次走一步,追上就有环
class ListNode1
{
Integer data;
ListNode1 next=null;
public ListNode1(Integer data)
{
this.data=data;
}
}
public class testCycleNode {
public static boolean ifHasCycle(ListNode1 head)
{
ListNode1 pfast=head;
ListNode1 pslow=head;
if(head.next==null)
return false;
while(pfast!=null)
{
pfast=pfast.next.next;
pslow=pslow.next;
if(pfast==pslow)
return true;
}
return false;
}
public static void main(String[] args) {
// 测试用例
ListNode1 first1=new ListNode1(1);
System.out.println(ifHasCycle(first1));
ListNode1 first2=new ListNode1(1);
ListNode1 second2=new ListNode1(1);
first2.next=second2;
second2.next=first2;
System.out.println(ifHasCycle(first2));
ListNode1 first3=new ListNode1(1);
ListNode1 second3=new ListNode1(1);
ListNode1 third3=new ListNode1(1);
ListNode1 f3=new ListNode1(1);
first3.next=second3;
second3.next=third3;
third3.next=f3;
f3.next=second3;
System.out.println(ifHasCycle(first3));
ListNode1 first4=new ListNode1(1);
ListNode1 second4=new ListNode1(1);
ListNode1 third4=new ListNode1(1);
ListNode1 f4=new ListNode1(1);
first4.next=second4;
second4.next=third4;
third4.next=f4;
System.out.println(ifHasCycle(first4));
}
}
2、判断环的入口
第一步求出环的步数,即第一次快慢指针相遇的地方
第二步让一个指针从head出发,和刚才的指针一起走,再次相遇则是环的入口
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
if(pHead==null||pHead.next==null)return null;
ListNode pfast=pHead;
ListNode pslow=pHead;
while(pfast!=null)
{
pfast=pfast.next.next;
pslow=pslow.next;
if(pfast==pslow)
{
pslow=pHead;
while(pfast!=pslow)
{
pfast=pfast.next;
pslow=pslow.next;
}
break;
}
}
return pslow;
}
}