public static ListNode detectCycle(ListNode head) {
if(head == null) {
return null;
}else if(head.next == head) {
return head;
}else{
ListNode slowP = head, fastP = head;
boolean is = false;
while(fastP.next != null && fastP.next.next != null) {
slowP = slowP.next;
fastP = fastP.next.next;
if(slowP == fastP) {
is = true;
break;
}
}
if(is) {
if(slowP == head || slowP.next == slowP) {
return slowP;
}else {
boolean find = false;
ListNode tcur = head,start = slowP;
while(tcur != null && !find) {
start = slowP;
do{
if(start == tcur) {
find = true;
break;
}
start = start.next;
}while(start != slowP);
if(find){
break;
}
tcur = tcur.next;
}
return tcur;
}
}else{
return null;
}
}
}
142. Linked List Cycle II
最新推荐文章于 2024-07-09 23:43:07 发布