/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
// if(head == null){
// return null;
// }
// ListNode slow = head.next;
// if(slow == null){
// return null;
// }
// ListNode fast = slow.next;
// while(fast != null){
// slow = slow.next;
// if(fast.next != null)
// fast = fast.next.next;
// if(fast == slow){
// while(head != slow){
// if(slow == null){
// return null;
// }
// slow = slow.next;
// head = head.next;
// }
// return head;
// }
// }
// return null;
if(head == null){
return null;
}
ListNode slow = head.next;
if(slow == null){
return null;
}
ListNode fast = slow.next;
while(fast != slow){
if(fast == null){
return null;
}
slow = slow.next;
if(fast.next != null)
fast = fast.next.next;
if(fast == slow){
while(head != slow){
if(slow == null){
return null;
}
slow = slow.next;
head = head.next;
}
return head;
}
}
return null;
}
}
代码中第一个是可以通过的第二个不可以通过,区别在于第一个里边我是直接判断fast!=null;第二个是fast!=slow,但是存在一种情况在刚开始就出现slow==fast所以不够严谨,只能判断非空,然后判断他们是否相等。