一、对于单向链表中如何确定是否有环?
设置快慢指针快指针每次走两步慢指针每次走一步,如果有环一定会相遇,即fast==slow;
二、有环的时候,快慢指针相遇后该如何确定环的入口在哪个节点呢?
相遇后fast回到head起始处,slow从相遇点开始和fast每次走一步,下一次相遇的节点便是环的入口。
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null)
return null;
ListNode fast=head;
ListNode slow=head;
ListNode pos_c=head;
int flag=0;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
if(fast==slow){
fast=head;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return slow;
}
}
return null;
}