感觉也没啥区别呀
我的代码:
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null) return null;
ListNode fast = head;
ListNode slow = head;
while(fast != slow){
if(fast == null || fast.next == null){
return null;
}
slow = slow.next;
fast = fast.next.next;
}
fast = head;
while( fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
无法通过的 case:
输入
[3,2,0,-4]
1
输出
tail connects to node index 0
预期结果
tail connects to node index 1
可以通过的代码:
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null) return null;
ListNode fast = head;
ListNode slow = head;
while(true){
if(fast == null || fast.next == null){
return null;
}
slow = slow.next;
fast = fast.next.next;
if(fast == slow) break;
}
fast = head;
while( fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
