Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
【分析】
由于每一个父亲只有可能有一个孩子,故这里的环实际上是指list中某一个节点的孩子同时也是它自己或者他的祖先。 这个问题需要注意几种情况:
空链表不成环
一个节点自环
一条链表完整成环
不能开额外的空间,即空间复杂度是o(1)。该问题是经典面试问题,其标准解法是用两个指针,一快一慢,如果在快的指针能够追上慢的指针,则有环,否则无环。
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null)
return false;
ListNode slow=head;
ListNode fast=head;
while (fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if (slow==fast)
return true;
}
return false;
}
}