题目地址
快慢指针判断是否有环,这个是基本功。
这题用哈希表记录出现过的结点很简单,找第一个重复的即可,但是空间复杂度非O(1)
卡了半天没做出来,看了代码随想录的题解,妙啊
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null || head.next==null){
return null;
}
ListNode hair=new ListNode();
hair.next=head;
ListNode slow=head;
ListNode fast=head;
boolean atBegin=true;
//快走2,慢走1
while(true){
if(slow==fast){
if(atBegin){
atBegin=false;
}else{
break;//找到了相遇点,即存在环
}
}
if(fast.next==null || fast.next.next==null){
return null;//无环
}
slow=slow.next;
fast=fast.next.next;
}
ListNode p1=hair.next;
ListNode p2=slow;
while(p1!=p2){
p1=p1.next;
p2=p2.next;
}
return p1;
}
}