这道题其实是一个非常经典的快慢指针的问题 ,也成为Floyd的乌龟和兔子算法。
设置两个指针,一个快指针,一个满指针,都从头节点开始遍历,如果链表中存在环,那么快指针最终会在环内某个节点相遇,如果不存在环,那么快指针会先到达链表的末尾(即null)
下面是java代码:
class ListNode {int val;ListNode next;ListNode(int x){val=x;}
}
public class LinkList{public boolean hasCycle(ListNode head){if(head==null||head.next==null){return false;}ListNode slow=head;ListNode fast=head.next;while (slow!=fast){if(fast==null||fast.next==null){return false;}slow=slow.next;fast=fast.next.next;}return true;}
}