142. 环形链表 II
package leetcode; public class demo_142 { public ListNode detectCycle(ListNode head) { //快慢指针,快指针一次走两个节点 ListNode fast=head; ListNode slow=head; //判断当前链表是否存在一个环 while(fast!=null) { if(fast.next!=null) { fast=fast.next.next; } else { return null; } slow =slow.next; //存在环 if(slow==fast) { break; } } //不存在环 if(fast==null) {return null;} //若存在一个环,则pre和slow总会在换入口时相遇 ListNode pre=head; while(pre!=slow) { pre=pre.next; slow=slow.next; } return pre; } }
浙公网安备 33010602011771号