Linked List Cycle
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which
represents the position (0-indexed) in the linked list where tail connects
to. If pos is -1, then there is no cycle in the linked list.
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null){
return false;
}
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){//考虑有环无环的临界情况
//无环fast.next!=null 有环fast!=null
if(fast==slow){
return true;
}
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
return true;
//有环的出口,要把这一句放到指针移动之后,不然进入循环
//之后,二个指针都等于head,就一定会返回true,指针移动之后在判断是否相等
//就没问题了,或者初始化的时候直接移动两个指针fast=fast.next.next
//slow=slow.next,就没有顺序问题了
}
return false;
}
}