Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
做过类似的题,思路是一个指针(fast)一次走两步,另一个指针一次走一步(head),如果这俩能碰头,说明有循环,大神的python代码比较简洁,通过异常捕捉省略了判断的语句,所以记录下,
def hasCycle(self, head):
try:
slow = head
fast = head.next
while slow is not fast:
slow = slow.next
fast = fast.next.next
return True
except:
return False
我的解法
public class Solution {
public boolean hasCycle(ListNode head) {ListNode fast=head;
if(head==null)
return false;
while(fast.next!=null){
head=head.next;
if(fast.next.next!=null)
fast=fast.next.next;
else
return false;
if(head==fast)
return true;
}
return false;
}
}