- 使用快慢指针,快指针一次走两,慢指针一次走一
- 两指针肯定会在环内相遇
/*
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;
}
//判断是否只有一个环
if(pHead==pHead.next)
{
return pHead;
}
ListNode low=pHead.next;
ListNode fast=pHead.next;
if(pHead.next.next!=null)
{
fast=pHead.next.next;
}
else
{
return null;
}
//肯定会在一圈内相遇
while(low!=fast)
{
low=low.next;
fast=fast.next.next;
if(fast==null)
{
return null;
}
}
fast=pHead;
System.out.println(fast.val);
low=low;
System.out.println(low.val);
while(fast!=low)
{
fast=fast.next;
low=low.next;
}
return low;
}
}